SQLEXCEPTION Operation not allowed after ResultSet closed error insist - java

Hello i need to do 2 active jobs with database in java.Firstly I did with 1 statement but after I read hints in here they said that I should use 2 statement.But although it still get Operation not allowed after ResultSet closed error.
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e){
System.err.println("Driver yok");
return;
}
Connection con=null;
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/kutuphane","root","");
System.out.println("Veritabnı baglandıldı");
Statement stmt=con.createStatement();
String strSQL="UPDATE emanetler SET IADETARIH='"+strdate+"' WHERE KISIAD='"+jTextField1.getText()+"' "
Statement stmt2=con.createStatement();
stmt.execute(strSQL);
ResultSet rs=stmt2.executeQuery("SELECT * FROM kitaplar");
while(rs.next()){
if(rs.getString("KITAPAD").equals(jTextField2.getText())){
strSQL="UPDATE kitaplar SET KITAPADET="+rs.getInt("KITAPADET")+"+1 WHERE KITAPAD='"+jTextField2.getText()+"' ";
stmt2.execute(strSQL);
}
}
stmt.close();
stmt2.close();
}
catch(SQLException e){
System.out.println("Veritabanı baglanmadi");
e.printStackTrace();
}

First you are using stmt2 object
ResultSet rs=stmt2.executeQuery("SELECT * FROM kitaplar");
Then in while loop
strSQL="UPDATE kitaplar SET KITAPADET="+rs.getInt("KITAPADET")+"+1 WHERE KITAPAD='"+jTextField2.getText()+"' ";
stmt2.execute(strSQL);
This must be corrected to use a separate Statement Object in While Loop to execute queries.
Hope this helps

Related

PSQLException: This ResultSet is closed.

Im having this problem that I cant do a executeQuery and then a executeUpdate in the same method it gives me "PSQLException: This ResultSet is closed."
I have tried to create another statement and other ResultSet but with no success. I you have any Idea how you help me, I would appreciate it. Thanks
Statement stmt = pc.getStatement();
try
{
ResultSet rs = stmt.executeQuery("select * from artigos where
artigoc="+s);
while (rs.next())
{
int stock = rs.getInt("stock");
stmt.executeUpdate("update artigos set stock="+newStock+","
+ "vendidos="+newVendidos+" where artigoc="+s);
}
rs.close(); // muito importante depois da consulta!
} catch (Exception e) {
e.printStackTrace();
System.err.println("Problems retrieving data from db...");
}
The javadoc of Statement says:
All execution methods in the Statement interface implicitly close a current ResultSet object of the statement if an open one exists.
Use a different Statement object to execute the update.

Getting error "Operation not allowed after ResultSet closed" [duplicate]

This question already has answers here:
Getting java.sql.SQLException: Operation not allowed after ResultSet closed
(2 answers)
Closed 6 years ago.
Im getting the exception:
Operation not allowed after ResultSet closed
Where am I wrong?
code:
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","root");
Statement s=con.createStatement();
ResultSet rs1=s.executeQuery("Select * from items");
while(rs1.next()) {
q= (q+Integer.parseInt(rs1.getString("qty")));
//update items Set qty=5 where name='Maggi';
s.executeUpdate("update items SET qty="+q+" WHERE name='"+value+"'");
}
}
catch(Exception ee){
System.out.println(ee);
}
As you will need two different Statement Objects to execute the query and update parts try:
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","root");enter code here
Statement s=con.createStatement();
ResultSet rs1=s.executeQuery("Select * from items");
while(rs1.next()){
q= (q+Integer.parseInt(rs1.getString("qty")));
s=con.createStatement(); // <- create a new statement here
s.executeUpdate("update items SET qty="+q+" WHERE name='"+value+"'");
}
}
catch(Exception ee){
System.out.println(ee);
}
}
Also consider using a PreparedStatement and using set* method to avoid potential SQL Injection

Reading ResultSet: java.sql.SQLException: Operation not allowed after ResultSet closed

I'm trying to get information from a MySQL database. I can connect and do things such as insert data into tables fine, and although I receive a ResultSet, I can't read it. Here's my code:
public ResultSet executeQuery(String query) {
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
if (stmt.execute(query)) {
rs = stmt.getResultSet();
}
return rs;
}
catch (SQLException ex){
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
}
finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlEx) { } // ignore
stmt = null;
}
}
return null;
}
Trying to read the ResultSet:
ResultSet set = executeQuery("SELECT rank FROM players");
try {
while(set.next()) {
System.out.println(set.getInt("rank") + "");
}
} catch(Exception ex) {
ex.printStackTrace();
} finally {
try {
set.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
I get this error:
java.sql.SQLException: Operation not allowed after ResultSet closed
I've been looking around the internet and on different forums all day. What's wrong with my code?
Your finally block in executeQuery closes your statement before you've iterated over the results.
Well, two things -
1) I do not get why you have both execute() and executeQuery() in your method? I think executeQuery() should work for you.
2) Do not close the statement before iterating through resultset. Make it an instance variable and close it after iterating.
TL;DR Your executeQuery closes the Statement.
From the JavaDoc for Statement.close
Releases this Statement object's database and JDBC resources
immediately instead of waiting for this to happen when it is
automatically closed.
You close() your Statement before you read your ResultSet. Closing a Statement causes all of the ResultSet instances associate with that Statement to also be closed.
You need to pass in a Consumer<ResultSet> into a different method, and process the ResultSet whilst the Statement is open:
public void executeQuery(final String query, final Consumer<ResultSet> consumer) {
try(final Statement stmt = conn.createStatement();
final ResultSet rs = stmt.executeQuery(query)) {
consumer.accept(rs);
}
catch (SQLException ex){
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
}
}
I have also fixed your code:
I have replaced your try..finally with a try-with-resources
You execute your query twice by calling stmt.executeQuery(query) and then stmt.execute(query). This is not only wasteful, but you lose the reference to the first ResultSet and if Statement.close didn't close all the associated resultsets you would have had a memory leak.

Not able to retrieve data after executing preparatory statement in Eclipse after JDBC Connection

Here is the preparatory statement I am using after making jdbc connection (Using SQL Developer) but on execution I am getting the following error
resultsetoracle.jdbc.driver.OracleResultSetImpl#762f5aa3
I am able to retrieve data from database if not using preparatory statement. Not sure if the problem with the resultset I am using to see the results.
System.out.println("resultset" + rs);
Please help. Thanks in advance
I am using the following jar (OJDBC6-11.2.0.2.0)
public static void main(String[] argv) {
Connection conn= null;
PreparedStatement pstmt = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("connecting to a database");
//Making JDBC connection
conn = DriverManager.getConnection(url,userName,password);
System.out.println("Database connection successfully");
System.out.println("creating statement");
String query = "select * from event where externaleventid=?";
PreparedStatement pstmt = conn.prepareStatement(query);
//Bind values into the parameters.
pstmt.setString(1,"1256294");
ResultSet rs = pstmt.executeQuery();
System.out.println("resultset" + rs);
conn.close();
} catch(SQLException se){
se.printStackTrace();
} catch(Exception e){
e.printStackTrace();
} finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
}try {
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
That's not an error. What you are printing out is the toString of the result set, and not the contents of the result set. Try looping through rs.next().
You can do like rs.getString("mycolumn") to get the result for a column named "mycolumn" which is stringlike data (call appropriate methods for appropriate types) but you do have to loop through the result set using next(). The next() method returns a boolean to let you know when you are done. So:
while (rs.next()){
System.out.println(rs.getString("mycolumn"));
}
Both column positions (1,2,3,...) and column names are legitimate ways of addressing the columns
EDIT
In case this is helpful, how you find out number of columns in result set:
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
You can also do like
rsmd.getColumnType(1);
rsmd.getColumnLabel(1);
rsmd.getColumnDisplaySize(1);
to get further information about the column 1 for example.

Operation not allowed after ResultSet closed

Allright been trying to figure this out the last 2 days.
Statement statement = con.createStatement();
String query = "SELECT * FROM sell";
ResultSet rs = query(query);
while (rs.next()){//<--- I get there operation error here
This is the query method.
public static ResultSet query(String s) throws SQLException {
try {
if (s.toLowerCase().startsWith("select")) {
if(stm == null) {
createConnection();
}
ResultSet rs = stm.executeQuery(s);
return rs;
} else {
if(stm == null) {
createConnection();
}
stm.executeUpdate(s);
}
return null;
} catch (Exception e) {
e.printStackTrace();
con = null;
stm = null;
}
return null;
}
How can I fix this error?
It's hard to be sure just from the code you've posted, but I suspect that the ResultSet is inadvertently getting closed (or stm is getting reused) inside the body of the while loop. This would trigger the exception at the start of the following iteration.
Additionally, you need to make sure there are no other threads in your application that could potentially be using the same DB connection or stm object.
IMHO, you should do everything you need with your ResultSet before you close your connection.
there are few things you need to fix. Opening a connection, running a query to get the rs, closing it, and closing the connection all should be done in the same function scope as far as possible. from your code, you seem to use the "con" variable as a global variable, which could potentially cause a problem. you are not closing the stm object. or the rs object. this code does not run for too long, even if it has no errors. Your code should be like this:
if (stringUtils.isBlank(sql)){
throw new IllegalArgumentsException ("SQL statement is required");
}
Connection con = null;
PreparedStatement ps =null;
Resultset rs = null;
try{
con = getConnection();
ps = con.preparestatement(sql);
rs = ps.executeQuery();
processResults(rs);
close(rs);
close(ps);
close(con);
}catch (Execption e){
log.Exception ("Error in: {}", sql, e);
throw new RuntimeException (e);
}finally{
close(rs);
close(ps);
close(con);
}
use another Statement object in inner loop
Like
Statement st,st1;
st=con.createStatement();
st1=con.createStatement();
//in Inner loop
while(<<your code>>)
{
st1.executeQuery(<<your query>>);
}
I know this is a few years late, but I've found that synchronizing the db methods usually get rid of this problem.

Categories

Resources