JDBC: Use batch to process multiple SQL statements (sxt)
Demo
- Import java. SQL .*;
- Public class testbatch
- {
- /**
- * @ Use batch to process multiple SQL statements
- */
- Public static void main (string [] ARGs)
- {
- // 1. Do not use preparedstatement
- /*
- * Connection conn = NULL; statement stmt = NULL; string url =
- * "JDBC: mysql: // localhost: 3306/College"; string user = "root"; string
- * Password = "123456 ";
- *
- * Try {class. forname ("com. MySQL. JDBC. Driver"); Conn =
- * Drivermanager. getconnection (URL, user, password); stmt =
- * Conn. createstatement (); stmt. addbatch ("insert into user
- * Values (301, 'go1', '20170', '0') "); stmt. addbatch (" insert into user
- * Values (302, 'go2 ', '000000', '00') "); stmt. addbatch (" insert into user
- * Values (303, 'go3', '000000', '000 ')");
- *
- * Stmt.exe cutebatch ();
- *} Catch (classnotfoundexception e) {// todo auto-generated catch
- * Block E. printstacktrace ();} catch (sqlexception e) {// todo
- * Auto-generated Catch Block E. printstacktrace ();} finally {try {
- * If (stmt! = NULL) {stmt. Close (); stmt = NULL;} If (Conn! = NULL ){
- * Conn. Close (); Conn = NULL;
- *}
- *} Catch (sqlexception e) {// todo auto-generated Catch Block
- * E. printstacktrace ();}}
- *}
- */
- // 2. Use preparedstatement for processing
- Connection conn = NULL;
- Preparedstatement pstmt = NULL;
- String url = "JDBC: mysql: // localhost: 3306/College ";
- String user = "root ";
- String Password = "123456 ";
- Try
- {
- Class. forname ("com. MySQL. JDBC. Driver ");
- Conn = drivermanager. getconnection (URL, user, password );
- Pstmt = conn. preparestatement ("insert into user values (?,?,?,?) ");
- Pstmt. setint (1,401 );
- Pstmt. setstring (2, "goo1 ");
- Pstmt. setstring (3, "A1 ");
- Pstmt. setstring (4, "K1 ");
- Pstmt. addbatch ();
- Pstmt. setint (1,402 );
- Pstmt. setstring (2, "goo2 ");
- Pstmt. setstring (3, "A2 ");
- Pstmt. setstring (4, "K2 ");
- Pstmt. addbatch ();
- Pstmt. setint (1,403 );
- Pstmt. setstring (2, "goo3 ");
- Pstmt. setstring (3, "A3 ");
- Pstmt. setstring (4, "K3 ");
- Pstmt. addbatch ();
- Pstmt.exe cutebatch ();
- } Catch (classnotfoundexception E)
- {
- // Todo auto-generated Catch Block
- E. printstacktrace ();
- } Catch (sqlexception E)
- {
- // Todo auto-generated Catch Block
- E. printstacktrace ();
- } Finally
- {
- Try
- {
- If (pstmt! = NULL)
- {
- Pstmt. Close ();
- Pstmt = NULL;
- }
- If (Conn! = NULL)
- {
- Conn. Close ();
- Conn = NULL;
- }
- } Catch (sqlexception E)
- {
- // Todo auto-generated Catch Block
- E. printstacktrace ();
- }
- }
- }
- }