java_ first year _JDBC (3)

Affairs

When we connect to the database via JDBC and start interacting, by default is automatically submitted, sometimes because in order to maintain the integrity of business processes, improve performance, or use distributed transactions, need to start to support the transaction at this time is to call Connection setAutoCommit object (); boolean false pass off submitted automatically by default:

conn.setAutoCommit(false);

Commit the transaction:

conn.setAutoCommit();

Database rollback:

conn.rollback();

With the rollback of the database, we can save the first set point, you can define a new save point, releaseSavepoint (Savepoint savepointName) can delete a saved point by the method setSavepoint (String savepointName) Connection object; deepen understanding of the following examples:

try{
    conn.setAutoCommit(false);
    stmt = conn.createStatement();
    Savepoint savepoint1 = conn.setSavepoint("DELETED_1");
    String SQL = "DELETE FROM employees WHERE ID =100";
    stmt.executeUpdate(SQL);
    conn.rollback(savepoint1);
    Savepoint savepoint2 = conn.setSavepoint("DELETED_2");
    SQL = "DELETE FROM employees WHERE ID =101";
    stmt.executeUpdate(SQL);
    conn.commit();
}catch(An SQLException e) { 
      e.printStackTrace (); 
}  

abnormal

For JDBC, the most common abnormality is java.sql.SQLException to be processed.

After an exception occurs redirects catch clause, if there is no corresponding catch clause, the execution of the program will end.

Handle exceptions has the following methods:

 

 Batch processing SQL statements

You need to use DatabaseMeteData.supportsBatchUpdates () method to confirm that the target database supports batch processing, support will be returned if true;

By increasing addBatch Statement of interactive objects () SQL statement, then the batch processing by the executeBatch () method which returns an array of integers, each element corresponding update statement update count; may be used clearBatch () method to remove SQL statements , will all addBatch () statement increases are deleted, can not remove the specified statement

Statement stmt = conn.createStatement();
conn.setAutoCommit(false);
String SQL = "INSERT INTO employees (id,age,first,last) VALUES(200,30,'ZHAO','XIAO')";
stmt.addBatch(SQL);
String SQL = "INSERT INTO employees (id,age,first,last) VALUES(201,35,'JIA','XIAO')";
stmt.addBatch(SQL);
int[] count = stmt.executeBatch();
conn.commit

 

Guess you like

Origin www.cnblogs.com/lzj-learn/p/11590761.html