javaweb复习
1.jdbc
数据库连接对象Connection(功能1,2)
1.获取SQL对象
(1)Statement create Statement()
(2)PreparedStatement prepareStatement(sql)
(3)CallableStatement prepareCall(sql)
2.管理事务
事务管理:放在try 和catch中catch{中有回滚事务}
(1)开启事务
conn.setAutoCommit(boolean autoCommit);true 为自动提交事务,false为手动提交事务,即为开启事务
(2)提交事务:
conn.commit();
(3)回滚事务:
conn.roolback();
例子:
/** * */ package com.cainiao.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; /** * @author 86198 * */ public class JDBCDemo1_Connection { public static void main(String[] args)throws Exception { //1.注册驱动 //Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql:///stu?useSSL=false"; String username ="root"; String password ="604794"; Connection conn = DriverManager.getConnection(url,username,password); //定义sql String sql1="update stu set money=3000 where id =1"; String sql2="update stu set money=3000 where id =2"; //获取执行sql的对象Statement Statement stmt = conn.createStatement(); try { //开启事务 conn.setAutoCommit(false);//开启事务 //5.执行sql int count1=stmt.executeUpdate(sql1); //6.处理结果 System.out.println(count1); int count2 = stmt.executeUpdate(sql2); System.out.println(count2); //提交事务 conn.commit(); } catch (Exception throwables) { //回滚事务 conn.rollback(); throwables.printStackTrace(); } //释放资源 stmt.close(); conn.close(); } }

浙公网安备 33010602011771号