In the development process, sometimes we need to execute multiple SQL statements, how to deal with this problem?
1, more than one statement execution error
Cause: An attempt was made to execute multiple SQL operations with a PreparedStatement object. The program will prompt for errors:
Operation not allowed after ResultSet closed
The RS is closed because it is executing while (Rs.next ()).
while (Rs.next ())
The above error is prompted when the query is set up again with preparedstatement statement = Con.preparestatement (SQL1).
To solve the problem of multiple operations above:
1, each SQL statement establishes a PreparedStatement object, and each PreparedStatement object operates on an SQL statement, which has little impact on program performance because JDBC performance consumption is primarily on the connection database.
Such as:
PStat = con.preparestatement ("Update userr set money=money-? where Name=? "); Pstat.setint (1, 100); Pstat.setstring (2, "John Doe"); Pstat.executeupdate (); PStat= Con.preparestatement ("Update userr set money=money+?") where Name=? "); Pstat.setint (1, 200); Pstat.setstring (2, "Zhang San"); Pstat.executeupdate (); PStat= con.preparestatement ("Update temp set count=count+?") where Name=? "); Pstat.setint (1, 1); Pstat.setstring (2, "Zhang San"); Pstat.executeupdate (); Con.commit ();
2,mysql batches so that you can manipulate multiple SQL statements by simply creating a PreparedStatement object.
PreparedStatement ps=conn.createstatement ();p s.addbatch ("Update user set money=money-100 where name= ' Zhang San '" );p S.addbatch ("Update user set money=money+100 where name= ' John Doe '");p s.addbatch ("Update temp set count= count+1 where Name= ' Zhang San ' ");p S.executebatch ();
Younger brother as a beginner, if there are deficiencies in the text, welcome criticism!
Java JDBC Multiple statement execution