JDBC第一天连接池案例
时间:2021-07-01 10:21:17
帮助过:2人阅读
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;
}
}
View Code
配置文件:
#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
View Code
JDBC第一天连接池案例
标签: