ds = new XxxDataSource();
ds.setXxx();
return ds;
2.配置文件
ds = new XxxDataSource();
加载配置文件
return ds;
数据源工具类 import com.alibaba.druid.pool.DruidDataSourceFactory; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.apache.commons.dbcp.BasicDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class DBUtils { //C3P0数据源 public class C3p0Util { public static ComboPooledDataSource ds = null; //初始化C3P0数据源 static { ComboPooledDataSource cpds = new ComboPooledDataSource(); //设置连接数据库需要的配置信息 try { cpds.setDriverClass("com.mysql.jdbc.Driver"); cpds.setJdbcUrl("jdbc:mysql://localhost:3306/shop"); cpds.setUser("root"); cpds.setPassword("root"); //设置连接池的参数 cpds.setInitialPoolSize(5);//初始连接数目 cpds.setMaxPoolSize(15);//最大连接数目 ds = cpds; } catch (Exception e) { throw new ExceptionInInitializerError(e); } } //返回数据源 public static ComboPooledDataSource getDataSource() { return ds; } } //Druid数据源 public static class DruidUtil { private static Properties properties = null; private static DataSource dataSource = null; private volatile static DruidUtil instatce = null; private Connection connection = null; //私有构造函数,防止实例化对象 private DruidUtil() { } static { try { properties = new Properties(); // 1.加载properties文件 InputStream is = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"); // 2.加载输入流 properties.load(is); // 3.获取数据源 dataSource = getDatasource(); } catch (IOException e) { e.printStackTrace(); } } //用简单单例模式确保只返回一个链接对象 public static DruidUtil getInstace() { if (instatce == null) { synchronized (DruidUtil.class) { if (instatce == null) { instatce = new DruidUtil(); } } } return instatce; } // 返回一个数据源 public DataSource getDataSource() { return dataSource; } // 返回一个链接 public Connection getConnection() { try { connection = dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return connection; } // 加载数据源 private static DataSource getDatasource() { DataSource source = null; try { source = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } return source; } } public class DbcpUtils { private static DataSource ds = null; private DbcpUtils() { } static { try { //获得配置文件路径 InputStream is = DbcpUtils.class.getClassLoader().getResourceAsStream("dbcp.properties"); //加载配置文件 Properties props = new Properties(); props.load(is); //创建数据源对象 ds = BasicDataSourceFactory.createDataSource(props); //关闭输入流 is.close(); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return ds.getConnection(); } public static void close(ResultSet rs, Statement st, Connection conn) { try { rs.close(); st.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)