JDBC 写数据库
以更新为例。
步骤
- 注册
mysql的驱动 - 获得一个连接
- 启动手动提交
- 创建一个更新
- 手动提交数据
- 关闭连接
- 异常回滚
1. 注册mysql的驱动
Class.forName("com.mysql.jdbc.Driver");
2. 获得一个连接
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
3. 启动手动提交
conn.setAutoCommit(false);
4. 创建一个更新
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "param");
int ret = stmt.executeUpdate();
5. 手动提交数据
conn.commit();
6. 关闭连接
stmt.close();
conn.close();
// 在 finally 里也得释放,避免程序抛出异常而无法释放。
finally {
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
7. 异常回滚
catch (Exception e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}

浙公网安备 33010602011771号