天天看点

Jdbc事务尝试一、代码

一、代码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcTest {

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("org.postgresql.Driver");
            connection = DriverManager.getConnection("jdbc:postgresql://192.168.162.139:5432/dsj", "test_schema", "[email protected]");
            if (connection == null) return;
            connection.setAutoCommit(false);
            statement = connection.createStatement();
            
            String sql1 = "truncate table INCREMENT_2";
            statement.addBatch(sql1);
            String sql2 = "insert into increment_2(djxh1) values (12)";
            statement.addBatch(sql2);

            statement.executeBatch();
            connection.commit();
            connection.setAutoCommit(true);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
            try {
                if (null != connection) connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            try {
                if (null != statement) statement.close();
                if (null != connection) connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
           
sql