package com.util.jdbc;import java.sql.Connection;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import com.alibaba.druid.pool.DruidDataSource;/** * JDBC封裝類 * @author DC * */public class JDBCUtils{ PRivate static DruidDataSource dataSource = new DruidDataSource(); //聲明線程共享變量 public static ThreadLocal<Connection> container = new ThreadLocal<Connection>(); //配置說明,參考官方網址 //http://blog.163.com/hongwei_benbear/blog/static/1183952912013518405588/ static{ dataSource.setUrl("jdbc:MySQL://182.92.222.140:3306/idotest?useUnicode=true&characterEncoding=UTF-8"); dataSource.setUsername("");//用戶名 dataSource.setPassWord("");//密碼 dataSource.setInitialSize(2); dataSource.setMaxActive(20); dataSource.setMinIdle(0); dataSource.setMaxWait(60000); dataSource.setValidationQuery("SELECT 1"); dataSource.setTestOnBorrow(false); dataSource.setTestWhileIdle(true); dataSource.setPoolPreparedStatements(false); } //禁止實體化該類 private JDBCUtils() {} /** * 獲取數據連接 * @return */ public static Connection connStart(boolean start){ Connection conn =container.get(); try{ if(conn!=null){ System.out.println(Thread.currentThread().getName()+"從map緩存中取得連接,Hashcode="+conn.hashCode()); }else{ System.out.println(Thread.currentThread().getName()+"從連接池中得到連接"); conn = dataSource.getConnection(); container.set(conn); } if(start){ conn.setAutoCommit(false);//開啟事務,默認事務級別為TRANSACTION_REPEATABLE_READ(4) } }catch(Exception e){ System.out.println("連接獲取失敗"); e.printStackTrace(); } return conn; } /***關閉連接*/ public static void connEnd(boolean end){ Connection conn=container.get(); if(conn!=null){ try{ if(end){ conn.commit(); conn.setAutoCommit(true); } }catch(Exception e){ System.out.println("事物提交異常"); try { if(end){ conn.rollback(); System.out.println(Thread.currentThread().getName()+"事務已回滾.....hashcode+"+conn.hashCode()); } } catch (Exception e1) { System.out.println("事物回滾異常"); e1.printStackTrace(); } e.printStackTrace(); }finally{ try { conn.close(); System.out.println(Thread.currentThread().getName()+"連接關閉"); container.remove();//從當前線程移除連接切記 System.out.println(Thread.currentThread().getName()+"成功移除連接。。。。"); } catch (Exception e2) { System.out.println("關閉連接異常,或者是移除緩存中的連接出錯.............."); e2.printStackTrace(); } } }else{ System.out.println("關閉連接時,連接為空"); } } public void aa(List<Integer> a,int b){ a.set(0, 2); b=2; } //簡單使用方式 public static void main(String[] args) throws SQLException { JDBCUtils j = new JDBCUtils(); List<Integer> a = new ArrayList<Integer>(); a.add(1); int b =1; j.aa(a,b); System.out.println(a.get(0)); System.out.println(b); }}
新聞熱點
疑難解答