db.properties内容:
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@$IP地址$:1521:tns数据库名
user=账号
pwd=密码
initsize=1
maxsize=10
代码如下:
import org.apache.commons.dbcp.BasicDataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* Created by zhangzubin on 2017/11/17.
*/
public class DBUtil {
private static BasicDataSource ds;
static {
Properties p = new Properties();
try {
//加载配置文件
p.load(DBUtil.class.getClassLoader()
.getResourceAsStream("db.properties"));
String driver = p.getProperty("driver");
String url = p.getProperty("url");
String user = p.getProperty("user");
String pwd = p.getProperty("pwd");
String initsize = p.getProperty("initsize");
String maxsize = p.getProperty("maxsize");
//创建连接池
ds = new BasicDataSource();
//注册驱动
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(user);
ds.setPassword(pwd);
ds.setInitialSize(new Integer(initsize));
ds.setMaxActive(new Integer(maxsize));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(
"初始化连接池失败!", e);
}
}
/**
* 通过连接池获取连接
*/
public static Connection getConnection()
throws SQLException {
return ds.getConnection();
}
/**
* 关闭连接
* */
public static void close(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(
"关闭连接失败!", e);
}
}
}
}