一:事物操做sql
public static void Transaction() throws SQLException { String sql1="update team set name='VVVV' where id=1"; String sql2="update team set name='HH啊哈哈' where id=2"; PreparedStatement stmt=null; Savepoint point=null; Connection con=SqlHelper.getConnection(); try{ con.setAutoCommit(false); //設置手動事物 /** * 第一次執行sql * */ stmt=con.prepareStatement(sql1); stmt.executeUpdate(); //設置事物回滾的點 point= con.setSavepoint(); //第二次執行sql stmt=con.prepareStatement(sql2); stmt.executeUpdate(); } catch(Exception ex){ //回滾到設置的回滾的位置 con.rollback(point); } finally{ //提交事物 con.commit(); SqlHelper.Distory(con, stmt); System.out.println("ok!"); } System.out.println("執行完畢~~~~~~~~~"); }
事物是經過Connection類操做的 默認是的con.setAutoCommit(true) 自動提交事物,在操做事務的時候能夠設置回滾的點 根據本身的需求回滾數據庫
二:批處理操做 爲了減小對數據庫的操做 提高性能 批量操做是數據庫不可缺乏的 具體例子以下 ```性能
public static void AddManyDate() throws SQLException{ String sql="INSERT INTO team(name,slogan,leader) values(?,?,?)"; PreparedStatement stmt=null; Connection conn=null; try { conn=SqlHelper.getConnection(); stmt=conn.prepareStatement(sql); //模擬批處理 for(int i=0;i<10;i++){ stmt.setString(1,"aaa"+i); stmt.setString(2, "bbb"+i); stmt.setString(3, "ccc"+i); //加入批處理 stmt.addBatch(); //建立一個執行策略 if(i%5==0){ //執行批量操做 stmt.executeBatch(); stmt.clearBatch(); } } stmt.executeBatch(); stmt.clearBatch(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ SqlHelper.Distory(conn, stmt); } System.out.println("執行完畢~~~~~~~~~"); }
主要的方法 PreparedStatement 類中的addBatch()、executeBatch();、clearBatch()這三個方法。 三 獲取自增加列的ID號
public static void getAuotKey() throws SQLException{ String sql="INSERT INTO team(name,slogan,leader) values(?,?,?)"; Connection conn=SqlHelper.getConnection(); PreparedStatement stmt= conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS); stmt.setString(1,"yyy"); stmt.setString(2, "gggg"); stmt.setString(3,"fffff"); stmt.executeUpdate(); ///獲取自動增加的咧 ResultSet res =stmt.getGeneratedKeys(); while(res.next()){ System.out.println(res.getString(1)); }
四 封裝通用的JDBC操做方法
private static Connection conn; private static PreparedStatement stmt; private static ResultSet set; public static String drive; public static String username; public static String password; public static String url;
/** * sql:傳入的slq語句 * param 傳入的參數 沒有參數穿入Null * [@return](http://my.oschina.net/u/556800) 返回boolean 值true 或者false * */
public static boolean insert(String sql,Object[] param){ int res=-1; boolean result=false; if(sql!=null && !"".equals(sql.trim())){ try { //獲取鏈接 conn=getConnection(); //建立執行單元 stmt=conn.prepareStatement(sql); if(param!=null&¶m.length>0){ //獲取佔位符 獲得參數的個數 int count=stmt.getParameterMetaData().getParameterCount(); for(int i=0;i<count;i++){ stmt.setObject(i+1, param[i]); } } //執行更新 stmt.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { Distory(conn, stmt); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return result; }
/** * sql:傳入的sql語句 * param:傳入的參數 * t:類對象 * [@throws](http://my.oschina.net/throws) SQLException * [@throws](http://my.oschina.net/throws) IllegalAccessException * [@throws](http://my.oschina.net/throws) InstantiationException * [@throws](http://my.oschina.net/throws) InvocationTargetException * */ public static <T> List<T> query(String sql,Object[] param,Class<T> clazz) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException{ List<T> list=new ArrayList(); T t=null; if(sql!=null && !"".equals(sql.trim())){ conn=getConnection(); stmt=conn.prepareStatement(sql); if(param!= null && param.length>0){ for(int i=0;i>param.length;i++){ stmt.setObject(i+1, param[i]); } } } //執行查詢 set= stmt.executeQuery(); ResultSetMetaData rsmd =stmt.getMetaData(); int columnCount= stmt.getMetaData().getColumnCount(); while(set.next()){ t=clazz.newInstance(); // 7. 遍歷每一行的每一列, 封裝數據 for (int i=0; i<columnCount; i++) { // 獲取每一列的列名稱 String columnName = rsmd.getColumnName(i + 1); // 獲取每一列的列名稱, 對應的值 Object value = set.getObject(columnName); // 封裝: 設置到t對象的屬性中 【BeanUtils組件】 BeanUtils.copyProperty(t, columnName, value); } // 把封裝完畢的對象,添加到list集合中 list.add(t); } return list; } /** * 加載數據庫驅動 * */ static{ try { Properties p=new Properties(); InputStream ins= SqlHelper.class.getResourceAsStream("/db.propertise"); p.load(ins); drive=p.getProperty("Driver"); username=p.getProperty("user"); password=p.getProperty("password"); url=p.getProperty("url"); Class.forName(drive); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 獲取鏈接 * */ public static Connection getConnection() throws SQLException{ conn=DriverManager.getConnection(url, username, password); return conn; } /** * 銷燬對象 * [@throws](https://my.oschina.net/throws) SQLException * */ public static void Distory(Connection conn,Statement stmt) throws SQLException{ if(conn!=null) conn.close(); if(stmt!=null) stmt.close(); } }