標籤:
1.properties 設定檔
driver=com.mysql.jdbc.Driver#urlurl=jdbc:mysql://localhost:3306/pabitel#useruser=root#passwordpassword=493656696
2.建一個用來擷取串連的類
1 public class DBHelper { 2 private DBHelper(){} 3 private static String url; 4 private static String driver; 5 private static String user; 6 private static String pwd; 7 private static ThreadLocal<Connection> tl=new ThreadLocal<Connection>(); 8 static{ 9 try {10 Properties prop=new Properties();11 InputStream is=DBHelper.class.getClassLoader().getResourceAsStream("properties.properties");12 prop.load(is);13 driver=prop.getProperty("driver");14 user=prop.getProperty("user");15 pwd=prop.getProperty("password");16 url=prop.getProperty("url");17 Class.forName(driver);18 } catch (Exception e) {19 e.printStackTrace();20 throw new RuntimeException(e);21 }22 }23 public static Connection getConnection() throws SQLException{24 Connection conn=DriverManager.getConnection(url,user,pwd);25 tl.set(conn);26 return conn;27 }28 public static void closeConnection(){29 Connection conn=tl.get();30 if(conn!=null){31 try {32 conn.close();33 } catch (SQLException e) {34 // TODO Auto-generated catch block35 e.printStackTrace();36 }37 tl.remove();38 }39 }40 }
3.threadlocal的使用
其類似於map,key-value組合,key為線程,value為connection
4.線程池的使用
定義線程池private static BasicDataSource ds;
後續在靜態塊中設定如下參數
1 ds=new BasicDataSource(); 3 ds.setDriverClassName(prop.getProperty("driver")); 4 ds.setUrl(prop.getProperty("url")); 5 ds.setUsername(prop.getProperty("user")); 6 ds.setPassword(prop.getProperty("psw")); 7 ds.setInitialSize(Integer.parseInt(prop.getProperty("initsize"))); 8 ds.setMaxActive(Integer.parseInt(prop.getProperty("maxactive"))); 9 ds.setMaxWait(Integer.parseInt(prop.getProperty("maxwait")));10 ds.setMinIdle(Integer.parseInt(prop.getProperty("minidle")));11 ds.setMaxIdle(Integer.parseInt(prop.getProperty("maxidle")));
即可用線程池來擷取串連。
JDBC串連mysql