上一篇文章是我們自己模擬的DBUtils工具類,其實有開發好的工具類 這裡使用commons-dbutils-1.6.jar 事務的簡單介紹: 在資料庫中應用事務處理案例:轉賬案例 張三和李四都有有自己的存款 主鍵 帳戶名 餘額 1 張三 1000 2 李四 10 要從張三的賬戶餘額中轉賬800到李 ...
上一篇文章是我們自己模擬的DBUtils工具類,其實有開發好的工具類
這裡使用commons-dbutils-1.6.jar
事務的簡單介紹:
在資料庫中應用事務處理案例:轉賬案例
張三和李四都有有自己的存款
主鍵 帳戶名 餘額
1 張三 1000
2 李四 10
要從張三的賬戶餘額中轉賬800到李四賬戶
SQL語句實現:
update xx set 餘額 = 餘額-800 where 主鍵=1
update xx set 餘額 = 餘額+800 where 主鍵=2
雖然操作成功,但是會出現問題,如果張三餘額不足800,那麼轉賬結束後餘額是負數,顯然有問題
而資料庫本身不會判斷是否為負數
所以資料庫就將這兩個操作包裝成一個事務,執行結果有兩種,成功或者失敗,不可以分開執行
執行成功稱:提交事務,執行失敗稱:回滾事務
對數據表的操作:
表的創建:
CREATE TABLE sort( sid INT PRIMARY KEY AUTO_INCREMENT, sname VARCHAR(100), sprice DOUBLE, sdesc VARCHAR(5000) );
QueryRunner類的方法實現表的增刪改:
package demo; import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; public class QueryRunnerDemo { private static Connection con = JDBCUtils.getConnection(); public static void main(String[] args) throws SQLException { // 這三個方法不能同時執行,測試時候應該註釋掉不使用的 // 因為每一個方法最後都關閉了資料庫連接 // insert(); // update(); delete(); } public static void insert() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "INSERT INTO sort (sname,sprice,sdesc)VALUES(?,?,?)"; Object[] params = { "籃球", 266, "體育用品" }; int row = qr.update(JDBCUtils.getConnection(), sql, params); System.out.println(row); DbUtils.closeQuietly(con); } public static void update() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "UPDATE sort SET sname=?,sprice=?,sdesc=? WHERE sid=?"; Object[] params = { "足球", 255, "出售足球", 8 }; int row = qr.update(con, sql, params); System.out.println(row); DbUtils.closeQuietly(con); } public static void delete() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "DELETE FROM sort WHERE sid=?"; int row = qr.update(con, sql, 8); System.out.println(row); DbUtils.closeQuietly(con); } } // 三種方法如果輸出1表示執行成功,輸出0表示執行失敗
自定義的工具:
package demo; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; public class JDBCUtils { private static Connection con; private static String driverClass; private static String url; private static String username; private static String password; static { try { readConfig(); Class.forName(driverClass); con = DriverManager.getConnection(url, username, password); } catch (Exception ex) { throw new RuntimeException("資料庫連接失敗"); } } private static void readConfig() throws Exception { InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("database.properties"); Properties pro = new Properties(); pro.load(in); driverClass = pro.getProperty("driverClass"); url = pro.getProperty("url"); username = pro.getProperty("username"); password = pro.getProperty("password"); } public static Connection getConnection() { return con; } }
配置文件:database.properties
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybase
username=root
password=xuyiqing
QueryRunner類查詢:
這裡有多種結果集的處理方式:
package demo; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Map; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.ArrayHandler; import org.apache.commons.dbutils.handlers.ArrayListHandler; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.MapHandler; import org.apache.commons.dbutils.handlers.MapListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; public class QueryRunnerDemo { private static Connection con = JDBCUtils.getConnection(); public static void main(String[] args) throws SQLException { arrayHandler(); arrayListHandler(); beanHandler(); beanListHandler(); scalarHandler(); mapHandler(); mapListHandler(); } public static void arrayHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort"; Object[] result = qr.query(con, sql, new ArrayHandler()); for (Object obj : result) { System.out.print(obj + "\t"); } // 列印第一行的數據 } public static void arrayListHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort"; List<Object[]> result = qr.query(con, sql, new ArrayListHandler()); for (Object[] objs : result) { for (Object obj : objs) { System.out.print(obj + "\t"); } System.out.println(); } // 列印了全部的數據 } public static void beanHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort"; Sort sort = qr.query(con, sql, new BeanHandler<Sort>(Sort.class)); System.out.println(sort); // 第一行的數據變成sort對象,列印對象的toString方法 // 這種方法需要特別註意:sort類中必須有空參構造器 } public static void beanListHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort"; List<Sort> list = qr.query(con, sql, new BeanListHandler<Sort>(Sort.class)); for (Sort s : list) { System.out.println(s); } // 所有數據變成sort對象,裝入list集合,列印出多個對象 } public static void scalarHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT COUNT(*) FROM sort"; long count = qr.query(con, sql, new ScalarHandler<Long>()); System.out.println(count); // 適合於處理單結果集 } public static void mapHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort"; Map<String, Object> map = qr.query(con, sql, new MapHandler()); for (String key : map.keySet()) { System.out.println(key + "\t" + map.get(key)); } // 列印第一行數據,鍵值對 } public static void mapListHandler() throws SQLException { QueryRunner qr = new QueryRunner(); String sql = "SELECT * FROM sort"; List<Map<String, Object>> list = qr.query(con, sql, new MapListHandler()); for (Map<String, Object> map : list) { for (String key : map.keySet()) { System.out.println(key + "\t" + map.get(key)); } } // 所有數據轉成map集合,再存入List集合 } }
附加:
這裡用到了和表名一致的一個自定義類,sort類:
package demo; public class Sort { private int sid; private String sname; private double sprice; private String sdesc; public Sort(int sid, String sname, double sprice, String sdesc) { this.sid = sid; this.sname = sname; this.sprice = sprice; this.sdesc = sdesc; } public Sort() { } public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public double getSprice() { return sprice; } public void setSprice(double sprice) { this.sprice = sprice; } public String getSdesc() { return sdesc; } public void setSdesc(String sdesc) { this.sdesc = sdesc; } @Override public String toString() { return "Sort [sid=" + sid + ", sname=" + sname + ", sprice=" + sprice + ", sdesc=" + sdesc + "]"; } }