JDBC连接mysql

1.properties 配置文件

driver=com.mysql.jdbc.Driver
#url
url=jdbc:mysql://localhost:3306/pabitel
#user
user=root
#password
password=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 block
35                 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")));

即可用线程池来获取连接。

 

posted @ 2015-12-07 23:18  pabitel  阅读(1407)  评论(0编辑  收藏  举报