Druid连接池和工具类
Druid:数据库连接池实现技术,由阿里巴巴提供的
1. 步骤:
1. 导入jar包 druid-1.0.9.jar
2. 定义配置文件:
* 是properties形式的
* 可以叫任意名称,可以放在任意目录下
3. 加载配置文件。Properties
4. 获取数据库连接池对象:通过工厂来来获取 DruidDataSourceFactory
5. 获取连接:getConnection
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
/**
* Druid演示
*/
public class DruidDemo01 {
public static void main(String[] args) throws Exception {
//1、导入jar包
//2、导入配置文件
//3、加载配置文件
Properties pro =new Properties();
InputStream is = DruidDemo01.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//4、获取连接池对象
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
//5、获取连接
Connection conn = ds.getConnection();
System.out.println(conn);
}
}
package utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* Druid连接池的工具类
*/
public class JDBCUtils {
//1、定义成员变量DataSource
private static DataSource ds;
static {
try {
//1、加载配置文件
Properties pro =new Properties();
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//2、获取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(Statement stmt,Connection conn){
if (stmt !=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn !=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs,Statement stmt,Connection conn){
if (rs !=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt !=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn !=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 获取连接池方法
*/
public static DataSource getDataSource(){
return ds;
}
}
package druid;
import utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 使用新的工具类
*/
public class DruidDemo02 {
public static void main(String[] args) {
/**
* 完成添加操作:给student表添加一条记录
*/
Connection conn=null;
PreparedStatement pstmt=null;
try {
//1、获取连接
conn = JDBCUtils.getConnection();
//2、定义sql
String sql="insert into student values(null,?,?)";
//3、获取pstmt对象
pstmt=conn.prepareStatement(sql);
//4、给?赋值
pstmt.setString(1,"张志伟");
pstmt.setInt(2,19);
//5、执行sql
int count = pstmt.executeUpdate();
System.out.println(count);
} catch (SQLException e) {
e.printStackTrace();
}finally {
//6、释放资源
JDBCUtils.close(pstmt,conn);
}
}
}