连接池类
package connection_druid;
import com.alibaba.druid.pool.DruidDataSource;
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;
public class JDBCUtils_druid {
private static DataSource dataSource;
static {
try {
Properties properties = new Properties();
properties.load(JDBCUtils_druid.class.getClassLoader().getResourceAsStream("druid.properties"));
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(Connection conn, Statement statement) {
if (conn != null) {
try {
conn.close(); //归还连接
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static Connection getconnection() throws SQLException {
return dataSource.getConnection();
}
public static void close2(ResultSet rs, Connection conn, Statement statement) {
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static DataSource data(){
return dataSource;
}
}
配置文件
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/gb1
username=root
password=123456
initialSize=5
#初始化连接数
maxActive=10
#最大连接数
maxWait=3000
#最大等待时间
主测试类
package connection_druid;
import Connection_c3p0.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class test_2 {
public static void main(String[] args) {
Connection getconnection =null;
PreparedStatement preparedStatement =null;
try {
getconnection = JDBCUtils_druid.getconnection();
//调用连接池类,获取连接对象
String str = "insert student value (null,?,?,?)";
//编写SQL语句,插入student一条数据
preparedStatement = getconnection.prepareStatement(str);
preparedStatement.setString(1,"猫耳女同事");
preparedStatement.setInt(2,135);
preparedStatement.setInt(3,4);
int i = preparedStatement.executeUpdate();
//返回该SQL语句影响的行数
System.out.println(i);
} catch (Exception throwables) {
throwables.printStackTrace();
}finally {
JDBCUtils_druid.close(getconnection,preparedStatement);
//使用连接池类,进行资源的释放,与连接的归还
}
}
}