Hi I a have MySql installed with Netbeans and have been trying to use Java with MySQL, however I am running into an issue when I run it. My database is called "test" and my table is "task". The two columns I have are: "id", and "task" (and I realized that naming a variable the same as the table probably is not a good idea). I also have a side question in the code area asking what it does. This is the error:
run:
May 22, 2015 11:52:25 PM databasetest.DatabaseTest main
SEVERE: Operation not allowed after ResultSet closed
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:804)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6986)
at databasetest.DatabaseTest.main(DatabaseTest.java:43)
BUILD SUCCESSFUL (total time: 41 seconds)
This is my code:
package databasetest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DatabaseTest {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement pst = null;
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "cinder";
try {
String author = "Trygve Gulbranssen";
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
//^^ what is VERSION? What is this supposed to be doing?
for (int i=1; i<=1000; i++) {
String query;
query = "INSERT INTO task(task) VALUES(" + 2*i + ")";
st.executeUpdate(query);
}
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseTest.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(DatabaseTest.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
SELECT VERSION() is meant to tell you your MySQL version. First, print the result of the SELECT then run your other queries. Running intermediate insert queries with the Statement implicitly closes the ResultSet, hence your error. Move
if (rs.next()) {
System.out.println(rs.getString(1));
}
before you run
for (int i=1; i<=1000; i++) {
// String query;
String query = "INSERT INTO task(task) VALUES(" + 2*i + ")";
st.executeUpdate(query);
}
Related
Can anybody help me to get actual column name and its alias using ResultSetMetaData by connecting to sqlserver database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
class MysqlCon {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=alcoa", "sa", "test");
Statement stmt = con.createStatement();
String query = "SELECT std_code as \"Student code\" from Student ";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsm =rs.getMetaData();
for (int i = 1; i <= rsm.getColumnCount(); i++) {
System.out.println(rsm.getColumnLabel(i) + "--" + rsm.getColumnName(i));
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
output
Student code--Student code
Above code works as expected in other database like mysql and oracle.
I checked code for SQLServerResultSetMetaData. Both methods getColumnLabel and getColumnName are identical.
abzycdxw65, has raised same issue on their github account. it is closed.
Is there any way to get following output:
Student code--std_code
If I get your question you can try the followings to retrieve column names
select name from sys.columns
I've updated J/connector in my program from Connector 5.1.7 to Connector 5.1.39 and I saw selections stop working.
After digging more I realize that only ordered selects don't work. If I remove the order by from sql query everything is nice.
Here is my program
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MysqlVersion {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&character_set_server=utf8mb4&useSSL=false";
String user = "root";
String password = "root";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("select * from `scripts` order by id desc");
//this returns false when order by is in the query
System.out.println(rs.next());
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MysqlVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MysqlVersion.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
Always System.out.println(rs.next()); will return false when 'order by' is in query.
If I go back to earlier version everything works ok. Am I doing something wrong. Is there a special setup I need to do? Or this is a bug?
I'm using MySql 5.7.14
I am working in command prompt this is my code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnf) {
System.out.println("Driver could not be loaded: " + cnf);
}
}
public static void main(String[] args)
{
String connectionUrl = "jdbc:mysql://localhost:3306/mysql";
String dbUser = "root";
String dbPwd = "admin";
Connection conn;
ResultSet rs;
String queryString = "SELECT ID, NAME FROM exptable";
try {
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
Statement stmt = conn.createStatement();
// INSERT A RECORD
stmt.executeUpdate("INSERT INTO exptable (name) VALUES (\"TINU K\")");
// SELECT ALL RECORDS FROM EXPTABLE
rs = stmt.executeQuery(queryString);
System.out.println("ID \tNAME");
System.out.println("============");
while (rs.next()) {
System.out.print(rs.getInt("id") + ".\t" + rs.getString("name"));
System.out.println();
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException sqle) {
System.out.println("SQL Exception thrown: " + sqle);
}
}
}
i am getting error like
java.lang.ClassNotFoundException and java.sql.SQLException
so may i know what mistake have i made
You might have missed the classpath in your java command. While executing from command prompt you must mention the class path along with your command.
java -cp
ex:
java -cp /home/test/jars:/home/test/src com.test.Lab
I am attempting to write a JUnit test for a query which is retrieved via a textbox in an html form. The text retrieval has been tested and works but my unit test is failing. I am using 2 relevant classes: QueryController and QueryControllerTest. I have been playing around with when and what I am closing in these two classes and keep getting the error: Operation not allowed after ResultSet closed.
QueryControllerTest.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import static org.junit.Assert.*;
public class QueryControllerTest {
#Test
public void testQuery() {
ResultSet testRs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/test";
String connectionUser = "root";
String connectionPassword = "GCImage";
conn = DriverManager.getConnection(connectionUrl,
connectionUser, connectionPassword);
Query testQuery = new Query();
testQuery
.setQuery("select * from service_request where FN_contact = 'Greg'");
testRs = QueryController.executeSelect(conn, testQuery);
assertEquals("Laughlin", testRs.getString("LN_contact"));
assertEquals("Hello World", testRs.getString("Notes"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
testRs.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
QueryController.java
import java.util.Map;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class QueryController {
#RequestMapping(value = "/query")
public String processRegistration(#ModelAttribute("query") Query query,
Map<String, Object> model) {
String queryString = query.getQuery();
if (queryString != null && !queryString.isEmpty()) {
System.out.println("query (from controller): " + queryString);
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/test";
String connectionUser = "root";
String connectionPassword = "GCImage";
conn = DriverManager.getConnection(connectionUrl,
connectionUser, connectionPassword);
if (queryString.toLowerCase().startsWith("select")) {
ResultSet rs = executeSelect(conn, query);
} else {
int rowsUpdated = executeUpdate(conn, query);
System.out.println(rowsUpdated + " rows updated");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return "query";
}
public static ResultSet executeSelect(Connection conn, Query query) {
ResultSet rs = null;
Statement stmt = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query.getQuery());
while (rs.next()) {
String id = rs.getString("ID");
String firstName = rs.getString("FN_Contact");
String lastName = rs.getString("LN_Contact");
String notes = rs.getString("Notes");
System.out.println("ID: " + id + ", First Name: " + firstName
+ ", Last Name: " + lastName + ", Notes: " + notes);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs!=null){
rs.close();
}
if(stmt != null){
stmt.close();
}
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rs;
}
}
QueryController.executeSelect is calling rs.close(), but then your assertEquals in QueryControllerTest.testQuery are calling methods on testRS. As executeSelect is returning the resultset, closing it first doesn't make sense. Further, executeSelect is being passed the connection, so it shouldn't be closing that either (what happens if the caller wants to do two different selects on the same connection?).
I think the problem is because you are creating two connections. Try to only instantiate the connection of QueryController class for your test. You will need to provide the connection. After you store it in a variable to run the query.
Connection con = QueryController.getConnection ();
I am new to Java and Oracle. I am trying to make an application that lists serial numbers of a product and when you click on a product's serial number from the list, it shows the other column informations from the database in a textbox. I have a form named CRUD.I am using Oracle 10g. Code is here:
package project1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class CRUD extends javax.swing.JFrame {
Connection connection = null;
public CRUD() {
try {
initComponents();
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
String serverName = "192.168.0.36";
String portNumber = "1521";
String sid = "XE";
String url = "jdbc:oracle:thin:#"+serverName+":"+portNumber+":"+sid;
String userName = "HR";
String password = "hr";
try {
connection = DriverManager.getConnection(url,userName,password);
} catch (SQLException ex) {
Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
}
try {
String temp="";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SERI_NO FROM KART");
while(rs.next()) // dönebildiği süre boyunca
{
String s = rs.getString("SERI_NO") ; //kolon isimleri oluşturuldu
temp+=s+"_";
}
Object [] tem_obj;
tem_obj=temp.split("_");
listOgrenciler.setListData(tem_obj);
} catch (SQLException ex) {
Logger.getLogger(edit.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, ex);
}
listOgrenciler.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent arg0) {
if (!arg0.getValueIsAdjusting()) {
try {
Statement stmtx = connection.createStatement();
Object[] sss=listOgrenciler.getSelectedValues();
String swhere="" ;
for (int i = 0; i < sss.length; i++) {
swhere+=sss[i].toString()+",";
}
swhere=swhere.substring(0,swhere.length()-1);
ResultSet rsx = stmtx.executeQuery("SELECT * FROM KART where SERI_NO in ("+swhere+")") ;
String temp="";
Object [] tem_obj;
tem_obj=temp.split("_");
String ara="";
for (int i = 0; i < tem_obj.length; i++) {
ara+=tem_obj[i].toString()+"\n";
}
texttoarea.setText(ara);
} catch (SQLException ex)
{
Logger.getLogger(edit.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
Errors i get are here:
20.Şub.2014 11:22:11 project1.CRUD$1 valueChanged
SEVERE: null
java.sql.SQLSyntaxErrorException: ORA-00904: "SNS080961097": invalid identifier
.....
at project1.CRUD$1.valueChanged(CRUD.java:78)
......
As I said before, I am new to both Java and Oracle. If the errors are so obvious don't laugh:)
Your this query
ResultSet rsx = stmtx.executeQuery("SELECT * FROM KART where SERI_NO in ("+swhere+")") ;
should be like this:
ResultSet rsx = stmtx.executeQuery("SELECT * FROM KART where SERI_NO in ('"+swhere+"')") ;
Actually there is no problems with you connection step to Oracle DB, its connected successfully, Your problem is within the query. make sure that you have a SERI_NO column in your KART table.
i suggest you to RUN the both same queries in you code from any SQL client such SQLDeveloper and see what these queries retrieve.
Observe this statement once,
swhere=swhere.substring(0,swhere.length()-1);
replace the above statement with the following
shere=swhere.substring(0,swhere.length()-2);
Because an extra comma(,) is included in your sql statement.
There is no issue with your connection.
Please add some logging to your code and you will know exactly where the error is throwing.
I guess the error is throwing in this line..
SELECT * FROM KART where SERI_NO in ("+swhere+")
You have to specify this as a string with '',where you actual select should look like below.
SELECT * FROM KART where SERI_NO in ('ABC','XCV');
so please check with this one check the value of the "swhere"