JDBC利用事務處理實現簡單增刪改查的詳解及工具類的建立
技術標籤:技術學習
JDBC全稱為:Java Data Base Connectivity (java資料庫連線),主要用於java與資料庫的連結。
整個連結過程如下圖:
jdbc中進行事務處理介紹
jdbc進行事務處理的語法
獲取連線物件con
設定con.setAutoCommit(false);//關閉事務的自動提交-》開啟事務
執行多條sql
對執行sql語句進行捕獲如果出現異常則con.rollback();回滾事務
執行成功則
con.commit(); 提交事務
// mysql預設開啟事務的自動提交
// 每執行1條SQL語句都是一個事務
Class.forName("com.mysql.jdbc.Driver" );
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/teacher", "root", "root");
try {
// 預設事務自動提交 每執行1條sql一個事務 其他事務不會影響該事務的執行
String sql = "update student set studentname='Bill' where studentid='2010005' ";
// 事務的開啟
// 在執行sql之前設定當前連線
// 將自動提交關閉
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement(sql);
ps.executeUpdate();
// 第二條sql語句報錯沒有執行成功 但是第一條資料已經執行成功存入資料庫
String sql2 = "update student set studesntage=28 where studentid='2010005' ";
PreparedStatement ps2 = con.prepareStatement(sql2);
ps2.executeUpdate ();
} catch (Exception e) {
// 對執行的sql語句程序try catch 如果出現異常回滾事務
con.rollback();
}
// 如果執行成功則提交事務將執行的結果儲存
con.commit();
1.資料庫驅動:Driver
載入mysql驅動:Class.forName(“com.mysql.jdbc.Driver”);
載入oracle驅動:Class.forName(“oracle.jdbc.driver.OracleDriver”);
載入相應的驅動需要匯入相應的包,如MySQL則需要匯入:mysql-connector-java-5.1.13-bin.jar
否則無法正常執行。
2.獲取資料庫連結:Connection
Connetion類主要用來連結資料庫,常通過DriverManager.getConnection()來獲取一個連線物件。
這裡有3個引數,分別是url,user,passwrod。對應的是要連結的資料庫,使用者名稱,密碼等。如:
url=jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8
user=root
password=root
3.執行sql語句:Statement
Statement物件用於執行sql語句,有以下3種:
(1)Statement物件用於執行不帶引數的簡單的SQL語句;
(2)PerparedStatement物件用於執行帶或不帶引數的預編譯SQL語句;
(3)CallableStatement物件用於執行對資料庫已儲存過程的呼叫;
Statement的常用方法:
(1)executeQuery()方法:執行查詢語句,返回ReaultSet物件。
(2)executeUpdata()方法:執行增,刪,改操作,返回更新的行數。
(3)addBatch(String sql) :把多條sql語句放到一個批處理中。
(4)executeBatch():向資料庫傳送一批sql語句執行。
4.結果集:ResultSet
執行executeQuery()方法後返回的結果集
常用方法:
(1)getString(String columnName):獲得當前行的某一string型別的欄位
(2)getFloat(String columnName):獲得當前行的某一string型別的欄位
(3)getDate(String columnName):獲得當前行的某一date型別的欄位
(4)getBoolean(String columnName):獲得在當前行的某一Boolean型別的欄位
(5)getObject(String columnName):獲取當前行的某一任意型別的欄位
(6)next():移動到下一行
實際程式碼
首先建立一個配置檔案,內容如下:
#資料庫驅動
driver=com.mysql.jdbc.Driver
#連線資料庫的URL
url=jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8
#使用者名稱
user=root
#密碼
password=root
**接著寫一個連線資料庫的通用工具類:**
public class DBUtil {
private static String driver;
private static String url;
private static String user;
private static String password;
static{
try {
//讀取配置檔案
InputStream in = DBUtil.class.getResourceAsStream("db.properties");
Properties properties = new Properties();
//載入配置檔案
properties.load(in);
//獲取配置檔案中的資料
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
//載入資料庫連結驅動
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取一個數據庫連結
*/
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, user, password);
}
}
實現簡單的增刪改查:
public class jdbcTest {
/**
* 建立表
*/
public static void createTable() throws SQLException{
String sql = "CREATE TABLE IF NOT EXISTS `user`("
+"`id` INT UNSIGNED AUTO_INCREMENT,"
+" `user_name` VARCHAR(100),"
+" `user_password` VARCHAR(100),"
+" `user_age` INT(11),"
+"PRIMARY KEY ( `id` )"
+")ENGINE=InnoDB DEFAULT CHARSET=utf8;";
Connection conn = DBUtil.getConnection();
//開啟事務
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
//提交事務
conn.commit();
//要注意關閉連線(在實際中最好不要像這樣關閉,最好標準一點)
conn.close();
}
**增加資料**
/**
* 增加資料
*/
public static void add() throws SQLException{
String sql = "INSERT INTO USER (user_name,user_password,user_age) VALUES('老王','123456',18)";
Connection conn = DBUtil.getConnection();
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
conn.commit();
conn.close();
}
刪除資料
```java
/**
* 刪除資料
*/
public static void delete() throws SQLException{
String sql = "DELETE FROM USER WHERE USER.user_name = '老王'";
Connection conn = DBUtil.getConnection();
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
conn.commit();
conn.close();
}
/**
* 修改資料
*/
public static void updata() throws SQLException{
String sql = "UPDATE USER SET USER.user_name = '老李'";
Connection conn = DBUtil.getConnection();
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.executeUpdate();
conn.commit();
conn.close();
}
**查詢資料**
```java
/**
* 查詢資料
*/
public static void query() throws SQLException{
String sql = "SELECT * FROM USER";
Connection conn = DBUtil.getConnection();
conn.setAutoCommit(false);
PreparedStatement preparedStatement = conn.prepareStatement(sql);
//執行查詢語句並返回結果集
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
//注意:這裡要與資料庫裡的欄位對應
String username = resultSet.getString("user_name");
String password = resultSet.getString("user_password");
String age = resultSet.getString("user_age");
System.out.println(username + " " + password + " " + age);
}
conn.commit();
conn.close();
}