JDBC 写数据库

以更新为例。

步骤

  1. 注册mysql的驱动
  2. 获得一个连接
  3. 启动手动提交
  4. 创建一个更新
  5. 手动提交数据
  6. 关闭连接
  7. 异常回滚

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();
      }
}
posted @ 2020-12-17 09:52  qianbuhan  阅读(138)  评论(0)    收藏  举报