jdbc之连接池
时间:2021-07-01 10:21:17
帮助过:4人阅读
/**
* @author Administrator
*第三方数据库连接池DBCP的应用
*/
public class demo1 {
public static void main(String[] args) {
Connection con =
null;
PreparedStatement pstmt =
null;
ResultSet rs =
null;
try {
InputStream in =
demo1.class.getClassLoader().getResourceAsStream(
"jdbc.properties");
Properties prop =
new Properties();
prop.load(in);
DataSource ds =
BasicDataSourceFactory.createDataSource(prop);
//这里的连接对象不同于DriverManager.getConnection中连接对象,
//其close方法已经被改造
con =
ds.getConnection();
pstmt = con.prepareStatement(
"select * from dog");
rs =
pstmt.executeQuery();
while (rs.next()) {
System.out.print(rs.getInt(
1) +
"\t");
System.out.print(rs.getString(
2) +
"\t");
System.out.print(rs.getInt(
3) +
"\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rs !=
null) {
//关闭存储查询结果的ResultSet对象
rs.close();
}
if (pstmt !=
null) {
//关闭负责执行SQL命令的Statement对象
pstmt.close();
}
if (con !=
null) {
//注意:关闭后,将连接返还给连接池,而不是给数据库
con.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
jdbc之连接池
标签:apache cat 执行sql trace handle dbcp puts static create