一、创建配置文件
在项目跟目录下,创建文件,输入“db.properties”文件名。
文件中的内容:(我用的是mysql数据库)
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/abc
username=root
password=123456
<!-- 初始化连接 -->
initialSize=10
<!--最大连接数量 -->
maxActive=50
<!-- 最大空闲连接 -->
maxIdle=20
<!-- 最小空闲连接 -->
minIdle=5
<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
二、加载配置文件:Properties对象
对应properties文件处理,开发中也使用Properties对象进行。我们将采用加载properties文件获得流,然后使用Properties对象进行处理。
JDBCUtils.java中编写代码
public class JDBCUtils {
private static String driver;
private static String url;
private static String user;
private static String password;
// 静态代码块
static {
try {
// 1 使用Properties处理流
// 使用load()方法加载指定的流
Properties props = new Properties();
Reader is = new FileReader("db.properties");
props.load(is);
// 2 使用getProperty(key),通过key获得需要的值,
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获得连接
*/
public static Connection getConnection() {
try {
// 1 注册驱动
Class.forName(driver);
// 2 获得连接
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}