一、前期准备
1.配置文件(druid.properties)
在使用 Druid 时候,这个文件可以随意放,我放到了src目录下。
url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
username=root
password=root
driverClassName=com.mysql.cj.jdbc.Driver
#最初连接数
initialSize=10
#最大连接数
maxActive=20
#最多等待时间
maxWait=1000
filters=wall
2.我的版本:
mysql 8.0.21
mysql-connector-java-8.0.21
druid-1.1.22.jar
二、工具类
1.成员变量
private static DataSource ds ;
2.静态代码块
static {
try {
//1.创建配置文件对象
Properties pro = new Properties();
//2.加载配置文件
pro.load(new FileReader("E:\\Java_IDEA\\project\\src\\druid.properties"));
//3.创建DataSource 连接池
ds =DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
3.获取连接对象
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
4.释放资源
第一个参数:连接数据库的对象
第二个参数:执行sql语句的对象
第三个参数:数据库返回的结果对象
public static void close(ResultSet result, Statement state ,Connection conn){
if (result != null){
try {
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (state != null){
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
二、Main
public class druid_Util_demo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstate = null;
try {
//获取连接池工具类中的连接对象
conn = Util_druid.getConnection();
String sql = "insert into account value (null,?,?)";
//执行sql语句对象
pstate = conn.prepareStatement(sql);
//设置数据
pstate.setString(1,"孙七");
pstate.setString(2,"55");
//输出结果
int count = pstate.executeUpdate();
System.out.println(count);
} catch (SQLException e) {
e.printStackTrace();
}finally {
//释放资源
Util_druid.close(null,pstate,conn);
}
}
}