Connection(数据库连接对象)作用:
1.获取执行SQL的对象
2.管理事务
public class JDBCDemo_shiwu {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.注册驱动
// Class.forName("com.mysql.jdbc.Driver");
//2.获取连接:如果连接的是本机MySQL并且端口是默认的3306,可以简化书写
String url="jdbc:mysql:///booklib?useSSL=false";
String username="root";
String password="123456";
Connection conn = DriverManager.getConnection(url, username, password);
//3.定义sql
String sql1 = "update book set bookName='海底两万里1' where bookNo = '01'";
String sql2 = "update book set bookName='海底两万里2' where bookNo = '01'";
//4.获取执行sql的对象 Statement
Statement stmt = conn.createStatement();
try {
//开启事务
conn.setAutoCommit(false);
//5.执行sql,返回受影响的行数
int count1 = stmt.executeUpdate(sql1);
System.out.println(count1);
int count2 = stmt.executeUpdate(sql2);
//6.处理结果
System.out.println(count2);
//提交事务
conn.commit();
}catch (Exception exception){
//回滚事务
conn.rollback();
exception.printStackTrace();
}
//7.释放资源
stmt.close();
conn.close();
}
}