自增主键回显
一般在插入数据时,设置主键为自增,然后我们就不用去维护这个主键值,其他的级联表可能以这个主键作为外键或参考,所以我们要拿到插入数据的主键值,这就是主键回显。
 如何获取数据库自增的主键值?
 在原生的JDBC中,实现主键回显非常简单。
- 创建PreparedStatement时,传入Statement.RETURN_GENERATED_KEYS这个常量,或直接传入“1”
PreparedStatement pstm = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
- 获取自增主键的结果集,这个结果集是一行一列,“id=值” 的形式
  
ResultSet rsKeys = pstm.getGeneratedKeys();  
if(rsKeys.next()){  
    System.out.println("自增长的主键是为"+rsKeys.getInt(1));  
    // 或
    System.out.println("自增长的主键值是"+ rsKeys.getString("GENERATED_KEY"));
}
批量插入
当利用原生的JDBC做批量插入时,性能非常低,看个模拟的例子
Class.forName("com.mysql.cj.jdbc.Driver");  
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?user=root&password=root");  
String sql = "insert into user(name,password,email,birthday) values(?,?,?,?)";  
PreparedStatement pstm = conn.prepareStatement(sql);  
pstm.setObject(1, "zhangsan");  
pstm.setObject(2, "123321");  
pstm.setObject(3, "123@com");  
pstm.setObject(4, "2023-01-10");  
long start = System.currentTimeMillis();  
int i = 1000;  
while(i -- > 0){  
    // 模拟批量插入1000次  
    pstm.executeUpdate();  
}  
long end = System.currentTimeMillis();  
System.out.println("共耗时" + (end - start) + " 毫秒");

 在学习MySQL时,在执行插入的SQL语句时,我们可以这样写,一次插入多个值
insert into user(name,password,email,birthday) values('zs','123','123','123'),('ls','222','222','333')
利用这个语法,JDBC封装了批量插入的方法,我们直接来使用即可。
- 在url后添加rewriteBatchedStatements=true,表示允许批量插入
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?rewriteBatchedStatements=true", "root", "root");
- 使用addBatch()方法追加值
// 此方法是将值追加到values后  
pstm.addBatch();
- 使用executeBatch()方法来执行批量插入
看一下这个批量插入的耗时
Class.forName("com.mysql.cj.jdbc.Driver");  
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc?rewriteBatchedStatements=true", "root", "root");  
String sql = "insert into user(name,password,email,birthday) values(?,?,?,?)";  
PreparedStatement pstm = conn.prepareStatement(sql);  
pstm.setObject(1, "zhangsan");  
pstm.setObject(2, "123321");  
pstm.setObject(3, "123@com");  
pstm.setObject(4, "2023-01-10");  
long start = System.currentTimeMillis();  
int i = 1000;  
while (i-- > 0) {  
    // 模拟批量插入1000次  
  
    // 此方法是将值追加到values后  
    pstm.addBatch();  
}  
pstm.executeBatch();  
  
long end = System.currentTimeMillis();  
System.out.println("共耗时" + (end - start) + " 毫秒");

注意
- sql语句为insert into 表名 values (), sql语句的末尾不能加分号";",否则无法追加value
- 执行时是调用的executeBatch()方法
事务操作
在原生的JDBC中,如何操作事务?
 在原生的JDBC中,默认开启事务的自动提交,所以我们要是想自己管理事务,需要先关闭事务的自动提交。
 一般按照这个结构执行事务
try{  
    // 关闭事务自动提交  
    conn.setAutoCommit(false);  
    
    // 执行数据库操作  
    
    // 提交事务  
    conn.commit();  
}catch (Exception e){  
    // 事务回滚  
    conn.rollback();  
}
注意:JDBC中,事务的基本要求:必须是同一个连接connection
 所以一般在业务层进行事务操作,DAO层负责接收这个连接对象并执行数据库操作。



















