JDBC第一天连接池案例
JDBC,JDBC的工具类JDBC
连接从连接池中拿:
创建连接池的语句:
package day01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.apache.commons.dbcp2.BasicDataSource; public class DBUtils { private static String driver = null; private static String url = null; private static String user = null; private static String password = null; private static BasicDataSource ds = null; //静态块 static{ Properties props = new Properties(); try { //路径使用包路径 String path = "day01/db.properties"; props.load( DBUtils.class.getClassLoader() .getResourceAsStream(path)); driver = props.getProperty("driver"); url = props.getProperty("url"); user = props.getProperty("user"); password = props.getProperty("password"); //ds中已经有了几个创建好的连接 ds = new BasicDataSource();//创建连接池 ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(user); ds.setPassword(password); ds.setInitialSize( Integer.parseInt(props.getProperty("intialSize"))); } catch (Exception e) { e.printStackTrace(); } } /*创建连接*/ public static Connection getConnection() throws ClassNotFoundException, SQLException{ Connection conn = null; if(ds!=null){ conn = ds.getConnection(); } return conn; } }
配置文件:
#key = value driver = oracle.jdbc.OracleDriver url = jdbc:oracle:thin:@localhost:1521:xe user = fengweijie password= 1070937053 #driver = com.mysql.jdbc.Driver #url = jdbc:mysql:localhost:3306/test?useUni intialSize = 10