Druid工具类
导入jar包和配置文件:我的博客
1.导入jar包和配置文件
2.项目文件
3.代码
工具类:
package druid;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
//druid连接池工具类
public class jdbcUtils {
private static DataSource ds;
static{
//1加载配置文件
Properties properties = new Properties();
InputStream inputStream = jdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
try {
//加载类到内存
properties.load(inputStream);
//2.获取配置文件
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//3.获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//4.释放连接
public static void close(PreparedStatement preparedStatement,Connection connection){
close(null,preparedStatement,connection);
}
public static void close(ResultSet rs,PreparedStatement preparedStatement, Connection connection){
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();//释放连接
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static DataSource getDs() {
return ds;
}
}
测试类
package druid;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Demo {
public static void main(String[] args) throws SQLException {
//获取链接
Connection connection = jdbcUtils.getConnection();
System.out.println(connection);
//定义sql
String sql = "update account set balance = balance + ? where id = ?";
//3.获取执行sql对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//设置sql
preparedStatement.setInt(1,1000);
preparedStatement.setInt(2,1);
//执行sql
preparedStatement.executeUpdate();
//释放资源
jdbcUtils.close(preparedStatement,connection);
}
}