Connection接口
l Jdbc程序中的Connection,它用于代表数据库的链接,Connection是数据库编程中最重要的一个对象,客户端与数据库所有交互都是通过connection对象完成的,这个对象的常用方法:
createStatement() |
|
prepareStatement(String sql) |
|
prepareCall(String sql) |
|
void |
setAutoCommit(boolean autoCommit) |
void |
commit() |
void |
rollback() |
面试题: 什么时候,需要把 setAtuoCommit设为 false?
答: 当有多个dml 同时执行,将其看做一个整体提交,则使用 事务管理 ,则需要把 setAutoCommit 设为false;
// 1加载驱动 Class.forName("oracle.jdbc.driver.OracleDriver"); // 2得到连接 ct = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", "scott", "tiger"); // 把事务设为不自动提交 ct.setAutoCommit(false); // 3.创建sql对象(Statement / PreparedStatement /CallableStatement) statement = ct.createStatement(); // 4.通过statement向数据库发出sql 指令. // 需求: 对emp表进行操作: 把SMITH 的sal -10 给 KING sal+10 statement.executeUpdate("update emp set sal=sal-10 where ename='SMITH'"); int i = 9 / 0; statement.executeUpdate("update emp set sal=sal+10 where ename='KING'"); // 提交所有事务 ct.commit();