代码改变世界

dbcp连接mysql

2017-02-25 14:04  如是我所闻  阅读(1514)  评论(0编辑  收藏  举报

1 参数

  driver:  com.mysql.jdbc.Driver  //标准格式

   url:       jdbc:MySQL://localhost:3306/happyfarm    // localhost:IP地址  3306:端口号  happyfarm:数据库名

  user:     root   //数据库用户名

  pwd:  Alivin //数据库密码

   

2 代码

  db.properties

    

1 driver=com.mysql.jdbc.Driver
2 url=jdbc:MySQL://localhost:3306/happyfarm
3 user=root
4 pwd=Alivin
5 
6 initSize=2
7 maxSize=5

 

  数据库连接

    

 1 package util;
 2 
 3 import java.io.IOException;
 4 import java.sql.Connection;
 5 import java.sql.SQLException;
 6 import java.util.Properties;
 7 
 8 import org.apache.commons.dbcp.BasicDataSource;
 9 
10 /**
11  * 连接数据库工具
12  * @author Administrator
13  *
14  */
15 public class DBUtil {
16     //连接池
17     private static BasicDataSource bds;
18     static{
19         try {
20             Properties p = new Properties();
21             //存储数据库信息的文件
22             p.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
23             //取出连接数据库的参数
24             String driver=p.getProperty("driver");
25             String url=p.getProperty("url");
26             String user=p.getProperty("user");
27             String pwd=p.getProperty("pwd");
28             //初始化时连接数,最大连接数
29             String initSize=p.getProperty("initSize");
30             String maxSize=p.getProperty("maxSize");
31             //设置连接池参数
32             bds=new BasicDataSource();
33             bds.setDriverClassName(driver);
34             bds.setUrl(url);
35             bds.setUsername(user);
36             bds.setPassword(pwd);
37             bds.setInitialSize(Integer.parseInt(initSize));
38             bds.setMaxActive(Integer.parseInt(maxSize));
39             
40         } catch (IOException e) {
41             e.printStackTrace();
42         }
43     }
44     
45     /**
46      * 得到Conneection连接
47      */
48     public static Connection getConn() throws SQLException{
49         return bds.getConnection();
50     }
51     
52     /**
53      * 归还Connection
54      * @param conn 需要关闭的Connection
55      */
56     public static void closeConn(Connection conn){
57             if(conn!=null){
58                 try {
59                     conn.close();
60                 } catch (SQLException e) {
61                     e.printStackTrace();
62                 }
63             }
64     }
65 }