package util; import java.beans.PropertyVetoException; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import com.alibaba.druid.pool.DruidDataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DBUtil2 { //key,value都是String类型的map private static Properties p = new Properties(); static { //通过当前线程获取一个类加载器,然后通过这个类加载器加载配置文件到流里面 //默认以src为根路径 InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"); //properties通过加载流的方式进行初始化 try { p.load(is); } catch (IOException e) { e.printStackTrace(); } } /** * 获取连接 * @return * @throws PropertyVetoException */ public static Connection getConn() { try { //加载驱动 Class.forName(p.getProperty("jdbc.driver")); } catch (ClassNotFoundException cnfe) { System.out.println("Error loading driver: " + cnfe); } Connection conn = null; try { //数据源是一个名为:DataSource的接口,我们要说的就是这个接口的三种实现方式 /* * 1.c3p0连接池创建数据源的方式 */ // ComboPooledDataSource cpds = new ComboPooledDataSource();//向上造型 // cpds.setDriverClass("oracle.jdbc.OracleDriver"); // cpds.setJdbcUrl("jdbc:oracle:thin:@127.0.0.1:1521:orcl"); // cpds.setUser("scott"); // cpds.setPassword("Oracle11g"); // //cpds.setMaxPoolSize(5); // conn = cpds.getConnection(); /* * 2.dbcp连接池创建数据源的方法 */ // BasicDataSource bds = new BasicDataSource(); // bds.setDriverClassName("oracle.jdbc.OracleDriver"); // bds.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:orcl"); // bds.setUsername("scott"); // bds.setPassword("Oracle11g"); // conn = bds.getConnection(); /* * 3.druid连接池创建数据源的方法 */ DruidDataSource dds = new DruidDataSource(); dds.setDriverClassName("oracle.jdbc.OracleDriver"); dds.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:orcl"); dds.setUsername("scott"); dds.setPassword("Oracle11g"); conn = dds.getConnection(); //DriverManager工具类getConnection静态方法来获取连接Connection(代码已经和数据库建立起了连接) // conn = DriverManager.getConnection(p.getProperty("jdbc.url"), p.getProperty("jdbc.username"), p.getProperty("jdbc.password")); } catch (SQLException e) { e.printStackTrace(); // } catch (PropertyVetoException e) { // e.printStackTrace(); } return conn; } /** * 鍏抽棴杩炴帴 */ public static void closeConn(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }