四种链接数据库

一、环境

   1、数据库驱动jar文件

   2、DBCP方法

Commons-dbcp.jar:连接池的实现

Commons-pool.jar:连接池实现的依赖库

资源文件

   3、c3p0方法:

c3p0-0.9.1.2.jar

配置文件:c3p0-config.xml

二、连接操作

   1.DriverManager方法;

Java代码   收藏代码
  1. import java.sql.Connection;  
  2.   
  3.  import java.sql.DriverManager;  
  4.   
  5.  import java.sql.SQLException;  
  6.   
  7.  public class DBConnection {  
  8.   
  9.         private static String driverClass = "com.mysql.jdbc.Driver";  
  10.   
  11.         private static String url = "jdbc:mysql://localhost:3306/test";  
  12.   
  13.         private static String username = "root";  
  14.   
  15.         private static String password = "123456";  
  16.   
  17.         private static Connection conn = null;  
  18.   
  19.         static{  
  20.   
  21.             try {  
  22.   
  23.                 //注册驱动  
  24.   
  25.                 // 不要把conn = DriverManager.getConnection(url, username, password);  
  26.   
  27.                  //放在这里。防止所有用户都用一个Connection  
  28.   
  29.                   Class.forName(driverClass);    
  30.   
  31.                  } catch (Exception e) {  
  32.   
  33.                           throw new RuntimeException(e);  
  34.   
  35.                  }  
  36.   
  37.        }  
  38.   
  39.        public static Connection getConnection() throws SQLException{  
  40.   
  41.             conn = DriverManager.getConnection(url, username, password);  
  42.   
  43.             return conn;  
  44.   
  45.       }  
  46.   
  47.    
  48.   
  49.    }  
  50.   
  51. import java.sql.Connection;  
  52.   
  53.  import java.sql.DriverManager;  
  54.   
  55.  import java.sql.SQLException;  
  56.   
  57.  public class DBConnection {  
  58.   
  59.         private static String driverClass = "com.mysql.jdbc.Driver";  
  60.   
  61.         private static String url = "jdbc:mysql://localhost:3306/test";  
  62.   
  63.         private static String username = "root";  
  64.   
  65.         private static String password = "123456";  
  66.   
  67.         private static Connection conn = null;  
  68.   
  69.         static{  
  70.   
  71.             try {  
  72.   
  73.                 //注册驱动  
  74.   
  75.                 // 不要把conn = DriverManager.getConnection(url, username, password);  
  76.   
  77.                  //放在这里。防止所有用户都用一个Connection  
  78.   
  79.                   Class.forName(driverClass);    
  80.   
  81.                  } catch (Exception e) {  
  82.   
  83.                           throw new RuntimeException(e);  
  84.   
  85.                  }  
  86.   
  87.        }  
  88.   
  89.        public static Connection getConnection() throws SQLException{  
  90.   
  91.             conn = DriverManager.getConnection(url, username, password);  
  92.   
  93.             return conn;  
  94.   
  95.       }  
  96.   
  97.    
  98.   
  99.    }  

 

2.使用DataSource子类方法;

资源文件DBConnection.properties

   driverClass = com.mysql.jdbc.Driver

   url = jdbc:mysql://localhost:3306/test

   username = root

   password = 123456

模拟数据连接池 DataSourcePool.java

 

Java代码   收藏代码
  1. package cn.langzi.jdbc.DataSource;  
  2.   
  3.        import java.io.InputStream;  
  4.   
  5.        import java.io.PrintWriter;  
  6.   
  7.        import java.lang.reflect.InvocationHandler;  
  8.   
  9.        import java.lang.reflect.Method;  
  10.   
  11.        import java.lang.reflect.Proxy;  
  12.   
  13.        import java.sql.Connection;  
  14.   
  15.        import java.sql.DriverManager;  
  16.   
  17.        import java.sql.SQLException;  
  18.   
  19.        import java.util.LinkedList;  
  20.   
  21.        import java.util.Properties;  
  22.   
  23.        import javax.sql.DataSource;  
  24.   
  25.        import javax.sql.DataSource;  
  26.   
  27.    
  28.   
  29.        public class DataSourcePool implements DataSource {  
  30.   
  31.    
  32.   
  33.        private static String url = null;  
  34.   
  35.        private static String username = null;  
  36.   
  37.        private static String password = null;  
  38.   
  39.        private static int size = 10;  
  40.   
  41.        private static LinkedList<Connection> list = new LinkedList<Connection>();   
  42.   
  43.        static{  
  44.   
  45.           try {  
  46.   
  47.                InputStream in = DataSourcePool.class.getClassLoader()  
  48.   
  49.                              .getResourceAsStream(  
  50.   
  51.                                "cn/langzi/jdbc/DataSource/DBConnection.properties");  
  52.   
  53.                Properties prop = new Properties();  
  54.   
  55.                prop.load(in);  
  56.   
  57.                Class.forName(prop.getProperty("driverClass"));  
  58.   
  59.                url = prop.getProperty("url");  
  60.   
  61.                username = prop.getProperty("username");  
  62.   
  63.                password = prop.getProperty("password");  
  64.   
  65.    
  66.   
  67.               } catch (Exception e) {  
  68.   
  69.                   throw new ExceptionInInitializerError(e);  
  70.   
  71.               }  
  72.   
  73.       }   
  74.   
  75.       private static DataSourcePool pool = new DataSourcePool();  
  76.   
  77.           //创建对象就初始化size个数据库连接  
  78.   
  79.       private DataSourcePool(){   
  80.   
  81.           for(int i=0;i<size;i++){   
  82.   
  83.              try {  
  84.   
  85.                     Connection conn = DriverManager.getConnection(url, username, password);  
  86.   
  87.                     System.out.println(conn);  
  88.   
  89.                     list.add(conn);  
  90.   
  91.                  } catch (SQLException e) {  
  92.   
  93.                          e.printStackTrace();  
  94.   
  95.                  }  
  96.   
  97.            }  
  98.   
  99.      }   
  100.   
  101.      public static DataSourcePool getInstance(){  
  102.   
  103.             return pool;  
  104.   
  105.       }   
  106.   
  107.       @Override  
  108.   
  109.       public Connection getConnection() throws SQLException {  
  110.   
  111.       if(list.size()>0){  
  112.   
  113.        //取到连接,即从list中弹出一个Connection 连接  
  114.   
  115.            final Connection conn = list.pop();  
  116.   
  117.        //动态代理,返回一个代理对象  
  118.   
  119.         return (Connection) Proxy.newProxyInstance(DataSourcePool.class.getClassLoade(), conn.getClass().getInterfaces(), new InvocationHandler(){  
  120.   
  121.        public Object invoke(Object proxy, Method method, Object[] args)  
  122.   
  123.           throws Throwable {   
  124.   
  125.            //如果Connection调用的是close方法就将连接返回给数据连接池  
  126.   
  127.               if(method.getName().equals("close")){  
  128.   
  129.                   list.push(conn);  
  130.   
  131.                   return null;  
  132.   
  133.                }  
  134.   
  135.               return method.invoke(conn, args);  
  136.   
  137.            }  
  138.   
  139.    
  140.   
  141.            });  
  142.   
  143.       }  
  144.   
  145.         //连接用完  
  146.   
  147.         throw new RuntimeException("对不起,服务器繁忙!!!");  
  148.   
  149.     }  
  150.   
  151.    
  152.   
  153.       @Override  
  154.   
  155.       public Connection getConnection(String username, String password)  
  156.   
  157. throws SQLException {  
  158.   
  159. // TODO Auto-generated method stub  
  160.   
  161. return null;  
  162.   
  163. }  
  164.   
  165.    
  166.   
  167. @Override  
  168.   
  169. public PrintWriter getLogWriter() throws SQLException {  
  170.   
  171. // TODO Auto-generated method stub  
  172.   
  173. return null;  
  174.   
  175. }  
  176.   
  177.    
  178.   
  179. @Override  
  180.   
  181. public int getLoginTimeout() throws SQLException {  
  182.   
  183. // TODO Auto-generated method stub  
  184.   
  185. return 0;  
  186.   
  187. }  
  188.   
  189.    
  190.   
  191. @Override  
  192.   
  193. public void setLogWriter(PrintWriter out) throws SQLException {  
  194.   
  195. // TODO Auto-generated method stub  
  196.   
  197.    
  198.   
  199. }  
  200.   
  201.    
  202.   
  203. @Override  
  204.   
  205. public void setLoginTimeout(int seconds) throws SQLException {  
  206.   
  207. // TODO Auto-generated method stub  
  208.   
  209.    
  210.   
  211. }  
  212.   
  213.    
  214.   
  215. @Override  
  216.   
  217. public boolean isWrapperFor(Class<?> iface) throws SQLException {  
  218.   
  219. // TODO Auto-generated method stub  
  220.   
  221. return false;  
  222.   
  223. }  
  224.   
  225.    
  226.   
  227. @Override  
  228.   
  229. public <T> T unwrap(Class<T> iface) throws SQLException {  
  230.   
  231. // TODO Auto-generated method stub  
  232.   
  233. return null;  
  234.   
  235. }  
  236.   
  237. }  
  238.   
  239.    
  240.   
  241. package cn.langzi.jdbc.DataSource;  
  242.   
  243. import java.sql.Connection;  
  244.     import java.sql.SQLException;  
  245.   
  246. public class DBConnection {  
  247.    public static Connection getConnection() throws SQLException{  
  248.      
  249.          Connection conn  = DataSourcePool.getInstance().getConnection();  
  250.          return conn;  
  251.  }  
  252. }  

 

DBCP方法:

  资源文件:dbcpconfig.properties

    driverClassName=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/test

username=root

password=123456

initialSize=10

maxActive=50

maxIdle=20

minIdle=5

maxWait=60000

连接数据库:

 

Java代码   收藏代码
  1. package cn.langzi.jdbc.DBCP;  
  2.   
  3.    
  4.   
  5. import java.io.IOException;  
  6.   
  7. import java.io.InputStream;  
  8.   
  9. import java.sql.Connection;  
  10.   
  11. import java.sql.SQLException;  
  12.   
  13. import java.util.Properties;  
  14.   
  15. import javax.sql.DataSource;  
  16.   
  17. import org.apache.commons.dbcp.BasicDataSourceFactory;  
  18.   
  19. public class DBConnection {  
  20.   
  21. private static DataSource dataSource = null;  
  22.   
  23. static {  
  24.   
  25. try {  
  26.   
  27. //获取资源文件  
  28.   
  29. InputStream in = DBConnection.class.getClassLoader().getResourceAsStream("cn/langzi/jdbc/DBCP/dbcpconfig.properties");  
  30.   
  31. Properties properties = new Properties();  
  32.   
  33. //加载资源文件  
  34.   
  35. properties.load(in);  
  36.   
  37. //建立数据工厂  
  38.   
  39. BasicDataSourceFactory dataSourceFactory =  new BasicDataSourceFactory();  
  40.   
  41. dataSource = dataSourceFactory.createDataSource(properties);  
  42.   
  43. catch (Exception e) {  
  44.   
  45. // TODO Auto-generated catch block  
  46.   
  47. e.printStackTrace();  
  48.   
  49. }  
  50.   
  51. }  
  52.   
  53.  public static Connection getConnection() throws SQLException{  
  54.   
  55.  return dataSource.getConnection();  
  56.   
  57.  }  
  58.   
  59. }  

 

c3p0方法:

  配置文件:c3p0-config.xml

 

Java代码   收藏代码
  1.  <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <c3p0-config>  
  4.   
  5. <named-config name="userApp">  
  6.   
  7. <property name="driverClass">com.mysql.jdbc.Driver</property>  
  8.   
  9. <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>  
  10.   
  11. <property name="user">root</property>  
  12.   
  13. <property name="password">123456</property>  
  14.   
  15. <property name="acquireIncrement">5</property>  
  16.   
  17. <property name="initialPoolSize">10</property>  
  18.   
  19. <property name="minPoolSize">10</property>  
  20.   
  21. <property name="maxPoolSize">20</property><!-- intergalactoApp adopts a different approach to configuring statement caching -->  
  22.   
  23. <property name="maxStatements">0</property>  
  24.   
  25. <property name="maxStatementsPerConnection">5</property>  
  26.   
  27. <!-- he's important, but there's only one of him -->  
  28.   
  29. <user-overrides user="master-of-the-universe">  
  30.   
  31. <property name="acquireIncrement">1</property>  
  32.   
  33. <property name="initialPoolSize">1</property>  
  34.   
  35. <property name="minPoolSize">1</property>  
  36.   
  37. <property name="maxPoolSize">5</property>  
  38.   
  39. <property name="maxStatementsPerConnection">50</property>  
  40.   
  41. </user-overrides>  
  42.   
  43. </named-config>  
  44.   
  45. </c3p0-config>  

 连接数据库:

Java代码   收藏代码
  1. package cn.langzi.jdbc.c3p0;  
  2.   
  3.    
  4.   
  5. import java.sql.Connection;  
  6.   
  7. import java.sql.ResultSet;  
  8.   
  9. import java.sql.SQLException;  
  10.   
  11. import java.sql.Statement;  
  12.   
  13.    
  14.   
  15. import javax.sql.DataSource;  
  16.   
  17.    
  18.   
  19. import com.mchange.v2.c3p0.ComboPooledDataSource;  
  20.   
  21.    
  22.   
  23. public class DbConnection {  
  24.   
  25. private static DataSource dataSource;  
  26.   
  27. static{  
  28.   
  29. dataSource = new ComboPooledDataSource("userApp");  
  30.   
  31. }  
  32.   
  33. public static Connection getConnectioon() throws SQLException{  
  34.   
  35. return dataSource.getConnection();  
  36.   
  37. }  
  38.   
  39. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值