1. 程式人生 > >jdbc的事務開啟

jdbc的事務開啟

nec cnblogs 基礎 rgs manage pda dsta 上進 spa

在這篇文章的基礎上進行修改,標紅的部分表示添加的代碼,同時附有註解解釋。

http://www.cnblogs.com/xyyz/p/7119076.html

  1 package com.xyyz.jdbc;
  2 
  3 import java.sql.Connection;
  4 import java.sql.DriverManager;
  5 import java.sql.PreparedStatement;
  6 import java.sql.ResultSet;
  7 
  8 import com.xyyz.utils.JDBCUtils;
  9 
 10 public
class JDBCDemo { 11 12 public static void main(String[] args) throws Exception { 13 query(); 14 insert(); 15 query(); 16 update(); 17 query(); 18 delete(); 19 query(); 20 } 21 22 /** 23 * 查詢代碼 24 * 25 *
@throws Exception 26 */ 27 public static void query() throws Exception { 28 Connection connection = JDBCUtils.getConnection(); 29 // 獲取數據庫連接 30 String sql = "select * from jdbctestdata"; 31 // 獲取預編譯對象 32 PreparedStatement prepareStatement = connection.prepareStatement(sql);
33 // 執行sql語句 34 ResultSet resultSet = prepareStatement.executeQuery(); 35 // 遍歷打印sql語句 36 while (resultSet.next()) { 37 System.out.println(resultSet.getInt(1) + "--" + resultSet.getString(2)); 38 } 39 // 關閉釋放資源 40 JDBCUtils.closeAll(resultSet, prepareStatement, connection); 41 } 42 43 /** 44 * 插入數據 45 */ 46 public static void insert() throws Exception { 47 // 獲取數據庫連接 48 Connection connection = JDBCUtils.getConnection(); 49 // 這裏開啟了事務,最後提交了,成功的插入了一條數據。 50 connection.setAutoCommit(false); 51 String sql = "insert into jdbctestdata value(?,?,?)"; 52 // 獲取預編譯對象 53 PreparedStatement prepare = connection.prepareStatement(sql); 54 prepare.setString(1, "6"); 55 prepare.setString(2, "小白"); 56 prepare.setString(3, "30"); 57 int i = prepare.executeUpdate(); 58 connection.commit(); 59 System.out.println("i=" + i); 60 // 關閉釋放資源 61 JDBCUtils.closeAll(null, prepare, connection); 62 } 63 64 /** 65 * 更新數據 66 */ 67 public static void update() throws Exception { 68 69 // 獲取數據庫連接 70 Connection connection = JDBCUtils.getConnection(); 71 // 這裏開啟了事務,但是沒有提交,所以最後的執行的修改沒有用。 72 connection.setAutoCommit(false); 73 String sql = "update jdbctestdata set name=? , age=? where id=?"; 74 // 獲取預編譯對象 75 PreparedStatement prepare = connection.prepareStatement(sql); 76 prepare.setString(1, "小紅"); 77 prepare.setString(2, "20"); 78 prepare.setString(3, "6"); 79 int i = prepare.executeUpdate(); 80 System.out.println("i=" + i); 81 // 執行sql語句 82 JDBCUtils.closeAll(null, prepare, connection); 83 } 84 85 /** 86 * 刪除數據 87 */ 88 public static void delete() throws Exception { 89 // 獲取數據庫連接 90 Connection connection = JDBCUtils.getConnection(); 91 String sql = "delete from jdbctestdata where id = ?"; 92 // 獲取預編譯對象 93 PreparedStatement prepare = connection.prepareStatement(sql); 94 prepare.setString(1, "6"); 95 int i = prepare.executeUpdate(); 96 System.out.println("i=" + i); 97 // 執行sql語句 98 JDBCUtils.closeAll(null, prepare, connection); 99 } 100 101 }

jdbc的事務開啟