一、基本使用
1.导入jar包 druid-1.2.4.jar
2.定义配置文件:
1.是properties形式的
2.可以叫任意名称,可以放在任意目录下
3.加载配置文件properties
4.获取数据库连接对象:通过工厂来获取DruidDataSourceFactory
5.获取连接:getConnection
druid.properties配置内容
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///db1
username=root
password=200079111zzk
initialSize=5
maxActive=10
maxWait=3000
示例
public static void main(String[] args) throws Exception {
Properties pro = new Properties();
InputStream is = DruidDemo0.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
Connection conn = ds.getConnection();
System.out.println(conn);
}
二、构造druid连接池的工具类
public class JdbcUtils {
private static DataSource ds;
static {//静态代码块
try {
//加载配置文件
Properties pro = new Properties();
pro.load(JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//从配置文件中获取datasource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException{
return ds.getConnection();
}
//释放资源
public static void close(ResultSet rs,Statement statement, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Statement statement, Connection conn){
close(null,statement,conn);
}
//获取连接池
public static DataSource getDataSource() {
return ds;
}
}
工具类的测试
public class DruidDemo1 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pre = null;
try {
//获取工具类的连接
conn = JdbcUtils.getConnection();
String sql = "insert into stu values(?,?)";
//获取prepareStatement对象
pre = conn.prepareStatement(sql);
//给?赋值
pre.setInt(1,6);
pre.setString(2,"zzkya");
//执行sql
int cnt = pre.executeUpdate();
System.out.println(cnt);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
finally {
//释放资源
JdbcUtils.close(pre,conn);
}
}
}
运行结果
原来的数据库表:
执行之后: