Statement and PreparedStatement batch update _jdbc

Source: Internet
Author: User
Tags rollback

Advantages: 1. Save delivery time. 2. Concurrent processing.

PreparedStatement:

1) Addbatch () adds a set of parameters to the PreparedStatement object.

2) ExecuteBatch () submits a batch of parameters to the database for execution, and returns an array of update counts if all the commands are executed successfully.

Statement:

1) The Addbatch (String sql) method adds an SQL statement to the batch cache.

2) ExecuteBatch () executes all SQL statements in the batch cache.

Note: When using bulk updates in PreparedStatement, you must set the parameters before using the Addbatch () method to add the cache. Only change, delete, or INSERT statements can be used in a bulk update.

Java Code    Statement batch processing and transaction code are as follows:   Package com.ambow.day20.jdbc.jdbctestcommitandrollback ;   import java.sql.connection;   import java.sql.sqlexception;   Import  java.sql.Statement;   import com.ambow.day19.jdbc.util.jdbcconandclo;  /*   *1, first set Auto commit to False, do not allow it to automatically submit    *2, manual submission (commit)    *3, after the completion of the submission of the site will be auto  Commit, revert to true,   *4, remember to rollback (rollback);   * */   When an exception occurs SqlException in the execution catch public class statementcommitandrollbacktest {       public  Static void main (string args[])  {            Connection con = null;            statement stm = null;           try {    &NBsp;           con =  Jdbcconandclo.getconnectionbao ();                stm = con.createstatement ();                con.setautocommit (false);                //  If no exception occurs, proceed to the try statement, or jump to the catch statement                 stm.addbatch ("Insert into student values, ' Tangbao ') , ' high number ', ') ';               stm.addbatch ( "Insert into student values (24, ' Wangding ', ' C # ',)");                stm.addbatch ("Insert into student values" (25, ' 王国云 ', ' Java ', 90 ) ");      &NBSp;        stm.addbatch ("Insert into student values" (26, ' Slip out ', ' English ',;   ')              Stm.addbatch ("Insert into student values, ' Wqde ', ' Java ',") ");                /*                * int[] executebatch ()  throws                * sqlexception submits a batch of commands to the database for execution, and returns an array of update counts if all the commands are executed successfully.                */                stm.executebatch ();                system.out.println ("Insert success!");         &nbsP;      // commit: If all inserts are successfully performed, the normal end                 con.commit ();                SYSTEM.OUT.PRINTLN ("submitted successfully!");                con.setautocommit (TRUE);               } catch  (sqlexception e )  {               e.printstacktrace ( );               try {       //rollback:  If an exception occurs, all completed operations in the database are revoked, rolled back to the transaction start state                     if  (!con.isclosed ())  {           &nbsP;            con.rollback ();                         system.out.println ("Commit failed, rollback.") ");                        con.setautocommit (true);                    }                } catch  (sqlexception e1)  {                    e1.printstacktrace ();                } finally {                    JDBCconandclo.closestatement (STM);                    jdbcconandclo.closeconnection (Con);                }           }        }  }   preparedstatement batch processing and transaction code are as follows:   package  com.ambow.day20.jdbc.jdbctestcommitandrollback;   import java.sql.connection;   Import  java.sql.PreparedStatement;   import java.sql.sqlexception;   import  com.ambow.day19.jdbc.util.jdbcconandclo;     /*   * PreparedStatement:   1.addbatch ()   Adds a set of parameters to the  preparedstatement object internal    2.executebatch ()   submits a batch of parameters to the database for execution. Returns an array of update counts if all of the commands are executed successfully.    *    */   Public class preparedstatementcommitandrollbacktest {       public static void main (String  Args[])  {           connection con = null ;           PreparedStatement pstm = null;               try {                // 1.  establish a connection with the database                 con = jdbcconandclo.getconnectionbao ();                // 2.  Execute SQL statements                // 1). First create PreparedStatement statement (send SLQ request):                pstm = con.preParestatement ("Insert into student values (?,?,?,?)");                con.setautocommit (FALSE); /1, first set Auto commit to False, do not let it automatically submit                 // 2)   Set SQL statement 1                pstm.setint (1, 33);                pstm.setstring (2, "Wangqin");                pstm.setstring (3,  "C + +");                pstm.setdouble (4, 78.5);                // 3)   Adds a set of parameters to the batch command for this  PreparedStatement  object.              &Nbsp; pstm.addbatch ();                // 2)   Set SQL statement 2                pstm.setint (1, 34);                pstm.setstring (2, "Wuytun");                pstm.setstring (3,  "C");                pstm.setdouble (4, 77);                // 3)   Adds a set of parameters to the batch command for this  PreparedStatement  object.                pstm.addbatch ();                // 2)   SET SQL statement 3                pstm.setint (1, 31);                pstm.setstring (2, "Tetet");                pstm.setstring (3,  "C + +");                pstm.setdouble (4, 90);                // 3)   Adds a set of parameters to the batch command for this  PreparedStatement  object.                pstm.addbatch ();                // 2)   SET SQL statement 4                pstm.setint (1, 32);                pstm.setstring (2, "Liug");       &NBSp;        pstm.setstring (3,  "C");                pstm.setdouble (4, 50);                // 3)   Add a set of parameters to this  preparedstatement In the batch command for the   object.                pstm.addbatch ();                // 4)   submits a batch of parameters to the database for execution. Returns an array of update counts if all of the commands are executed successfully.                pstm.executebatch ();                SYSTEM.OUT.PRINTLN ("Insert succeeded.") ");               //  if all the inserts have been successfully performed, The normal end                con.Commit ();//2, Manual commit (commit)                 SYSTEM.OUT.PRINTLN ("submitted successfully!");                con.setautocommit (TRUE);// 3, after the completion of the submission of the site will be auto commit, restored to true,              }  catch  (sqlexception e)  {                e.printstacktrace ();                try {                    //  If an exception occurs, all completed operations in the database are revoked, rolled back to the transaction start state                     if (!con.isclosed ()) {                    &nbSp;   con.rollback ();//4, remember to rollback (rollback);      When an exception occurs to perform a catch sqlexception                    System.out.println ("Insert failed, rollback.") ");                        con.setautocommit (true);                    }                } catch  (sqlexception e1)  {                    e1.printstacktrace ();                }            }finally{            &Nbsp;  jdbcconandclo.closepreparedstatement (pstm);                jdbcconandclo.closeconnection (Con);            }       }  }  

 

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.