Druid:数据库连接池实现技术,由阿里巴巴提供的
1. 步骤:
1. 导入jar包 druid-1.0.9.jar
2. 定义配置文件:
* 是properties形式的
* 可以叫任意名称,可以放在任意目录下
3. 加载配置文件。Properties
4. 获取数据库连接池对象:通过工厂来来获取 DruidDataSourceFactory
5. 获取连接:getConnection
package cn.itcast.DataSource.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCutil {
//1定义成员变量
private static DataSource ds;
static{
try {
//2加载文件
Properties prop=new Properties();
/*ClassLoader classLoader = JDBCutil.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("druid.properties");
prop.load();*/
prop.load(JDBCutil.class.getClassLoader().getResourceAsStream("druid.properties"));
//获得datasource
ds= DruidDataSourceFactory.createDataSource(prop);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void close(Connection conn, Statement stmt , ResultSet rs){
if(conn!=null){
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection conn,Statement stmt){
close(conn,stmt,null);
}
//获取连接池
public static DataSource getDataSource(){
return ds;
}
}
|
|