执行代码
package cn.it.datasource.druid;import cn.it.datasource.utils.JDBCUtils;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;/*** @program: day5* @description: 使用工具类* @author: xiflys* @create: 2021-05-13 23:15**/
public class Demo2 {
public static void main(String[] args) {
// 完成一个添加的操作// 获取连接PreparedStatement ps = null;Connection conn = null;try {
conn = JDBCUtils.getConn();String sql = "insert into laravel_cate values(null,?,?)";ps = conn.prepareStatement(sql);ps.setString(1, "图包02");ps.setInt(2, 2);int count = ps.executeUpdate();System.out.println(count);} catch (SQLException throwables) {
throwables.printStackTrace();}finally {
JDBCUtils.close(ps, conn);}}
}
工具类
package cn.it.datasource.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.定义一个成员变量private static DataSource ds;private String s;// 初始化赋值static{
try {
// 1.加载配置文件Properties pro = new Properties();pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));// 2.获取DataSourceds = DruidDataSourceFactory.createDataSource(pro);} catch (IOException e) {
e.printStackTrace();} catch (Exception e) {
e.printStackTrace();}}/*** 获取连接* @return* @throws SQLException*/public static Connection getConn() throws SQLException {
return ds.getConnection();}/*** 关闭对象* @param stmt* @param conn*/public static void close(Statement stmt,Connection conn){
close(null,stmt,conn);/*if(stmt != null){try {stmt.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if(conn != null){try {conn.close();} catch (SQLException throwables) {throwables.printStackTrace();}}*/}/*** 关闭对象* @param res* @param stmt* @param conn*/public static void close(ResultSet res, Statement stmt, Connection conn){
if(res!=null){
try {
res.close();} catch (SQLException throwables) {
throwables.printStackTrace();}}if(stmt != null){
try {
stmt.close();} catch (SQLException throwables) {
throwables.printStackTrace();}}if(conn != null){
try {
conn.close();} catch (SQLException throwables) {
throwables.printStackTrace();}}}/*** 获取连接池对象* @return*/public static DataSource getds(){
return ds;}}
配置文件
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/laravelimg
username=root
password=123456
# 初始化连接数量
initiaSize=5
# 最大连接数
maxActive=5
# 最大等待时间
maxWait=3000