package com.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class jdbcDemo1 { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver");//mysql5之后可以省了 String url="jdbc:mysql://localhost:3306/temp_db"; //如果连接本机可简写为:String url="jdbc:mysql:///temp_db"; String username="root"; String password="zl951750"; Connection conn = DriverManager.getConnection(url, username, password); String sql = "update account set money=500 where name = \"张三\"" ; PreparedStatement ps = conn.prepareStatement(sql); ps.executeUpdate(sql); ps.close(); conn.close(); } }
DriverManager
提示:
•在开发中,我们不使用DriverManager.registerDriver(new Driver());方式注册驱动,因为会导致驱动注册两次。
•MySQL 5之后的驱动包,可以省略注册驱动的步骤
•自动加载jar包中META-INF/services/java.sql.Driver文件中的驱动类
•Connection(数据库连接对象)作用:
1.获取执行 SQL 的对象
2.管理事务
•MySQL 事务管理:默认自动提交事务
开启事务:BEGIN; / START TRANSACTION;
提交事务:COMMIT;
回滚事务:ROLLBACK;
•JDBC 事务管理:Connection接口中定义了3个对应的方法
开启事务:setAutoCommit(boolean autoCommit):true为自动提交事务;false为手动提交事务,即为开启事务
提交事务:commit()
回滚事务:rollback()
PreparedStatement动态设置参数
执行增删改查操作
int executeUpdate():执行DML、DDL语句,不需要再传递sql
ResultSet executeQuery():执行DQL 语句,不需要再传递sql
package com.jdbc; import java.sql.*; public class jdbcDemo1 { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql:///temp_db?useSSL=false";// String username="root"; String password="zl951750"; Connection conn = DriverManager.getConnection(url, username, password); PreparedStatement ps1 = null; PreparedStatement ps2 = null; PreparedStatement ps3 = null; try{ conn.setAutoCommit(false);//开启事物 String sql1 = "update account set money=money-500 where id=? " ; ps1 = conn.prepareStatement(sql1); ps1.setInt(1,1); ps1.executeUpdate(); // int i=1/0; String sql2 = "update account set money= money+500 where id=? " ; ps2 = conn.prepareStatement(sql2); ps2.setInt(1,2); ps2.executeUpdate(); conn.commit(); String sql3 = "select * from account" ; ps3 = conn.prepareStatement(sql3); ResultSet sets= ps3.executeQuery(); while (sets.next()){ System.out.println(sets.getInt("id")); System.out.println(sets.getString("name")); System.out.println(sets.getInt("money")); } }catch (Exception throwables){ throwables.printStackTrace(); conn.rollback(); } if(ps1!=null){ ps1.close(); } if(ps2!=null){ ps2.close(); } conn.close(); } }