目录
主键回显
使用场景
当我们对主键列为自动增长的表进行新增操作时,得到的返回为受影响的行数,无法得到新增记录的主键数据,所以我们要使用主键回显的方式来获取新增记录的主键值。
在Java程序中获取数据库中插入新数据后的主键值,并赋值给Java对象,此操作为主键回显。
主要步骤
-
创建数据库连接:使用JDBC创建与数据库的连接。
-
准备SQL语句:编写插入数据的SQL语句。要获取生成的主键,需要在执行
prepareStatement
时传递Statement.RETURN_GENERATED_KEYS
参数。 -
执行SQL语句:通过
executeUpdate
方法执行新增操作。 -
获取生成的主键:使用
getGeneratedKeys
方法从ResultSet
中获取数据库生成的主键。 -
关闭资源:关闭
ResultSet
、Statement
、Connection
等资源,避免资源泄漏。
代码实现
@Test
public void testReturnPK() throws SQLException {
//1.注册驱动
// Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/atguigu", "root", "atguigu");
//3.创建preparedStatement对象,传入需要主键回显参数Statement.RETURN_GENERATED_KEYS
PreparedStatement preparedStatement = connection.prepareStatement("insert into t_emp (emp_name, emp_salary, emp_age)values (?, ?,?)",Statement.RETURN_GENERATED_KEYS);
//4.编写SQL语句并执行,获取结果
Employee employee = new Employee(null,"rose",666.66,28);
preparedStatement.setString(1,employee.getEmpName());
preparedStatement.setDouble(2,employee.getEmpSalary());
preparedStatement.setDouble(3,employee.getEmpAge());
int result = preparedStatement.executeUpdate();
//5.处理结果
if(result>0){
System.out.println("添加成功");
}else{
System.out.println("添加失败");
}
//6.获取生成的主键列值,返回的是resultSet,在结果集中获取主键列值
ResultSet resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()){
int empId = resultSet.getInt(1);
employee.setEmpId(empId);
}
System.out.println(employee.toString());
//7.释放资源(先开后关原则)
resultSet.close();
preparedStatement.close();
connection.close();
}
重要提示
确保数据库表中的主键字段设置为自增类型(如MySQL中的AUTO_INCREMENT
)。
在执行prepareStatement
时传递Statement.RETURN_GENERATED_KEYS
参数,否则无法获取生成的主键。
批量操作
使用场景
在执行对多条记录的插入、更新、删除操作时,如果使用一般的方式进行SQL语句操作,数据库与应用程序之间会存在较大的开销,耗时也会较长。
批量操作是指将多个SQL语句一起打包执行。
主要步骤
-
创建数据库连接:使用JDBC创建与数据库的连接。
-
关闭自动提交模式:为了更好的控制事务,可以关闭自动提交模式,并在操作结束后手动提交。
-
准备SQL语句:编写需要批量执行的SQL语句。
-
添加批处理操作:使用
addBatch
方法将多条SQL语句添加到批处理中。 -
执行批量操作:通过
executeBatch
方法一次性执行所有批处理操作。 -
提交事务:如果没有错误,可以手动提交事务。
-
处理异常:如果在批量操作过程中出现错误,进行回滚操作。
-
关闭资源:关闭
Statement
、Connection
等资源,避免资源泄漏。
代码实现
public class JdbcBatchProcessing {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 1. 创建数据库连接
conn = DriverManager.getConnection(url, user, password);
// 2. 关闭自动提交模式
conn.setAutoCommit(false);
// 3. 准备SQL语句
String sql = "INSERT INTO your_table_name (column1, column2) VALUES (?, ?)";
pstmt = conn.prepareStatement(sql);
// 4. 添加批处理操作
for (int i = 1; i <= 10; i++) {
pstmt.setString(1, "value" + i);
pstmt.setString(2, "another_value" + i);
pstmt.addBatch(); // 添加到批处理
}
// 5. 执行批量操作
int[] affectedRows = pstmt.executeBatch();
// 6. 提交事务
conn.commit();
System.out.println("Batch executed successfully!");
} catch (SQLException e) {
// 7. 处理异常,进行回滚
if (conn != null) {
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
} finally {
// 8. 关闭资源
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
重要提示
批处理大小:尽量控制每次批处理的大小(如1000条记录),以避免内存溢出或数据库压力过大。
错误处理:在批量操作中,如果某条语句失败,通常会导致整个批处理的回滚,因此需要特别小心地处理异常。