Java JDBC Multiple statement execution

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.