This question already has answers here:
Getting java.sql.SQLException: Operation not allowed after ResultSet closed
(2 answers)
Closed 4 years ago.
Can anyone point me in the write direction to solve the error: SQLException: Operation not allowed after ResultSet closed
Here is the code i believe the error occurs in
Statement stmt = con.createStatement();
String query1 = "";
String query2 = "";
int candidateNo = 42;
query1 = "SELECT * FROM Candidates WHERE CandidateNo = "+ candidateNo;
ResultSet rs = stmt.executeQuery(query1);
//If query can be completed then display name and prompt to continue
if(rs.next()){
query2 = "SELECT * FROM Achieved WHERE CandidateNo = " + candidateNo;
ResultSet ts = stmt.executeQuery(query2);
}
I have tried using resultset rs = null; to create the variable but the error still occurs
You are iterating over the ResultSet bound to a Statement , then while iterating, you are using the exact same Statement object to issue a new query and get and iterate over another ResultSet .
This won't work as long as you are not done with the processing of the first ResultSet, so consider using a distinct Statement object for your second query .
In your code you used 2 ResultSet executing the same Statement object (stmt)concurrently. Use different Statement Objects for both queries.
Related
This question already has answers here:
Get value from a ResultSet by name
(2 answers)
Closed 1 year ago.
I am trying to set a string value into DB using prepared statement and Result Set. But it inserts into DB row this "com.mysql.cj.jdbc.result.ResultSetImpl#fcd6521"
PreparedStatement check = connection.prepareStatement(
"SELECT buildingName FROM building GROUP BY buildingId HAVING buildingId = ?");
check.setInt(1, building_id);
ResultSet rs = check.executeQuery();
insert.setString(1, String.valueOf(rs));
insert.executeUpdate();
I think that you need to read the tutorial indicated by #user16320675
A ResultSet is a type of set. It has to be accessed like that:
//if you expects receive only one buildName you use a simple if, otherwise you have to use a loop and a list or something like that
String text;
if(rs.next()){
text = rs.getString(0);
}
//index it's related to buildingName
This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 4 years ago.
Hi I get an error message in the following code:
public Component createComponents(){
Panel pane = new Panel();
try{
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tondb?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("select * from activeemployees");
ResultSet myRs2 = null;
while (myRs.next()) {
myRs2 = myStmt.executeQuery("SELECT * FROM employee WHERE ID="+myRs.getString("IDnumber"));
pane.add(new Label(myRs2.getString("firstName")+","+myRs.getString("lastName"),20,20));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
return pane;
}
Here's the image attached:
Can not figure out why.
Why don't you use INNER JOIN in your query to make it simpler? I guess you don't need two separate sql statement and execute them separately. In stead you can use join query to merge the data from two tables employee and activeemployees and fetch data from there. It will be much faster, too.
You may try this new query in your resultset:
ResultSet myRs = myStmt.executeQuery("SELECT E.firstName AS firstName, E.lastName AS lastName FROM employee E INNER JOIN activeemployees A ON E.IDnumber = A.IDnumber");
And then, new ResultSet, myRs2 is not needed anymore. And you can use following code:
while (myRs.next()) {
pane.add(new Label(myRs.getString("firstName")+","+myRs.getString("lastName"),20,20));
}
You can't execute several queries on one statement because if you do you reset the previous result set. So in your example, when the query for myRs2 is first executed myRs is cleared. Create a separate statement object inside the loop.
See the doc for Statement
This question already has answers here:
Variable column names using prepared statements
(7 answers)
Closed 4 years ago.
In a university task I'm using JDBC to access a database. I wrote a finder-method that could find objects in a table by any value in any column that has integer values.
public ResultSet findSampleByAnyCol(String colName, Integer sampleId, Connection con) {
ResultSet rs = null;
String sql = "SELECT * FROM sample WHERE ? = ?";
try(PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setString(1, colName);
pstmt.setInt(2, sampleId);
rs = pstmt.executeQuery();
}catch(SQLException e) {
e.printStackTrace();
}
return rs;
}
I tested it and I'm sure the problem is that "?" for the colum nname doesn't work. The stack trace says "invalid number". But if I change the SQL statement to SELECT * FROM sample WHERE sampleid = ? it works fine.
Just found the answer here, it´s not possible to do that. The "?" is just for values. To have variable columnnames it´s inevitable to do it with an own string manipulation.
This question already has an answer here:
ResultSet is not for INSERT query? Error message: Type mismatch: cannot convert from int to String
(1 answer)
Closed 5 years ago.
I am getting a error on the resultset rs part where netbeans shows the error as
incompatible types:int cannot be converted to resultset
Class.forName("java.sql.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?useSSL=false", "root", "abc");
Statement stmt = conn.createStatement();
String query = "SELECT * FROM patient WHERE Mobile_No='" + mobno + "';"; /*Get the value from the database*/
ResultSet rs = stmt.executeUpdate(query);/*Part where the error is appearing*/
while (rs.next()) {
String Name = rs.getString("Name");
String Age = rs.getString("Age");
String Mobile = rs.getString("Mobile_No");
String gender = rs.getString("Gender");
String symptoms = rs.getString("Symptoms");
model.addRow(new Object[]{Name, Age, Mobile, gender, symptoms});
}
rs.close();
stmt.close();
conn.close();
Use stmt.executeQuery(String sql), it returns ResultSet.
If you want a ResultSet returned you should use executeQuery, not executeUpdate.
The stmt.executeUpdate(query); doesn't fit for an SELECT query.
You need to replace it by stmt.executeQuery(query);
Well the method executeUpdate returns a int not a results set, seen in the documentation here: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String)
the integer being return being either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
the method you are actually want to use is executeQuery and the documentation for that can be found at:
https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeQuery(java.lang.String)
According the Javadoc (https://docs.oracle.com/javase/9/docs/api/java/sql/Statement.html#executeUpdate-java.lang.String-), stmt.executeUpdate(query); returns an int and not a ResultSet object.
From the Javadoc :
Returns:
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
I think you must use stmt.executeQuery(query); instead, which return the ResultSet you expect. You're doing a SELECT and not an INSERT, UPDATE, or DELETE operation.
I believe people have already answered your question, which is statement.executeUpdate(query) returns the number of how many rows has been affected by executing the query, and you should use statement.executeQuery(query) instead ..
But this part String query = "SELECT * FROM patient WHERE Mobile_No = '" + mobno + "';" is very bad approach, it will leave the door opened for SQL injection, you should use PreparedStatement instead of Statement
This question already has answers here:
How do I get the size of a java.sql.ResultSet?
(15 answers)
Closed 8 years ago.
I need your assistant and help in getting the count of the values which are available in the resultset. The resultset is having 22 records and in the below code, it is printing the count starting from 1 to 23. Is there any way to get the total no. of records as 22 (one value only) or by subtracting the last value from the first value?
My code is below:
while (rs.next())
{
count=0;
name1=rs.getString("name");
out.println(rs.getRow());
}
I tried to use rs.first() and rs.last() and it produced the below error:
java.sql.SQLException: Invalid operation for forward only resultset :
first
I tried to add the arguments to the createstatement, but the same exception is there:
conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE, rs.CONCUR_READ_ONLY);
java.sql.SQLException: Invalid operation for forward only resultset :
last
Please help me in the above issue.
Try this:
int rowcount = 0;
if (rs.last()) {
rowcount = rs.getRow();
rs.beforeFirst();
}
EDIT:
You need to change the statement of your query like this so that you can use the rs.last()
Statement stmt = con.createStatement(rs.TYPE_SCROLL_INSENSITIVE);
ResultSet rs = stmt.executeQuery("Your query");
Check Oracle Docs
You can use MySQL's count(*)
try{
Statement stmt = connection.createStatement();
String selectquery = "select count(*) from YourTable";
ResultSet rs = stmt.executeQuery(selectquery);
rs.next();
System.out.println("Amount of rows :" + rs.getInt(1));
}
If you wanna count rows based on "name", then
try{
Statement stmt = connection.createStatement();
String selectquery = "select count(name) from YourTable";
ResultSet rs = stmt.executeQuery(selectquery);
rs.next();
System.out.println("Amount of rows :" + rs.getInt(1));
}