与c3p0不同,Druid的配置文件是properties形式的。而且Druid不像c3p0那样可以自动加载配置文件,Druid需要手动去指定配置文件,所以Druid的配置文件可以叫任意名称,并且可以放置在任意目录下。 1、导入druid-1.0.9.jar和mysql连接器。 2、配置文件druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
3、工具类
package 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 JdbcUtils_Druid {
private static DataSource ds;
static {
try{
Properties prop = new Properties();
prop.load(JdbcUtils_Druid.class.getClassLoader().getResourceAsStream("druid.properties"));
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 st){
close(conn,st,null);
}
public static void close(Connection conn, Statement st, ResultSet rs){
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//获取连接池
public static DataSource getDataSource(){
return ds;
}
}
4、测试类 package druidtest;
import utils.JdbcUtils_Druid;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet;
public class TestDruid2 { public static void main(String[] args) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try{ conn = JdbcUtils_Druid.getConnection(); String sql = “select * from test1 where id = ?”; ps = conn.prepareStatement(sql); ps.setInt(1,1); rs = ps.executeQuery(); while (rs.next()){ int id = rs.getInt(“id”); String name = rs.getString(“name”); System.out.println(“name:”+name+",id="+id); }
}catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtils_Druid.close(conn,ps,rs);
}
}
}
|