JDBC可以通过执行多个SQL语句实现一次插入多个表的操作。具体步骤如下:
1. 创建连接:通过JDBC API获取数据库连接。
2. 开启事务:通过Connection对象的setAutoCommit(false)方法关闭自动提交事务。
3. 执行多个SQL语句:通过Statement或PreparedStatement对象的executeUpdate()方法执行多个SQL语句,每个SQL语句对应一个数据表的插入操作。
4. 提交事务:通过Connection对象的commit()方法提交事务。
5. 关闭连接:通过Connection对象的close()方法关闭数据库连接。
示例代码如下:
```java
Connection conn = null;
Statement stmt = null;
try {
// 创建连接
conn = DriverManager.getConnection(jdbcUrl, username, password);
// 开启事务
conn.setAutoCommit(false);
// 执行多个SQL语句
stmt = conn.createStatement();
String sql1 = "INSERT INTO table1 (col1, col2) VALUES ('value1', 'value2')";
String sql2 = "INSERT INTO table2 (col3, col4) VALUES ('value3', 'value4')";
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
// 提交事务
conn.commit();
} catch (SQLException e) {
// 回滚事务
if (conn != null) {
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
} finally {
// 关闭连接
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
```
JDBC同时插入多表
最新推荐文章于 2023-09-07 19:06:47 发布