1.工具类
(1)根据配置和工厂得到DataSource对象
//先获取配置
Properties properties = new Properties();
//获取路径
InputStream resourceAsStream = JDBC_util_2.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(resourceAsStream);
//获取连接池对象
dataSource = DruidDataSourceFactory.createDataSource(properties);
(2)工具应该包含的方法
//获取连接对象
public static Connection getCon() throws SQLException {
return dataSource.getConnection();
}
//获取池子对象
public static DataSource getDataSource(){
return dataSource;
}
//关闭链接对象,实际是归还给池子
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 void close(Statement statement,Connection connection){
close(null,statement,connection);
}
}
3.完整工具类代码
public class JDBC_util_2 {
//定义DataSouce
private static DataSource dataSource;
//通过druid得到连接池
static {
try {
//先获取配置
Properties properties = new Properties();
//获取路径
InputStream resourceAsStream = JDBC_util_2.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(resourceAsStream);
//获取连接池对象
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接对象
public static Connection getCon() throws SQLException {
return dataSource.getConnection();
}
//获取池子对象
public static DataSource getDataSource(){
return dataSource;
}
//关闭链接对象,实际是归还给池子
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 void close(Statement statement,Connection connection){
close(null,statement,connection);
}
}
4,测试代码
public class Damo6 {
private static PreparedStatement preparedStatement;
private static Connection con;
private static ResultSet resultSet;
public static void main(String[] args) {
try {
con = JDBC_util_2.getCon();
String sql="select * from user1 where name=?";
//使用准备状态解决注入问题
preparedStatement = con.prepareStatement(sql);
//给占位符对号入座
preparedStatement.setString(1,"jiang");
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
String password = resultSet.getString("password");
System.out.println("密码是 "+password);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBC_util_2.close(resultSet,preparedStatement,con);
}
}
}
5.测试结果
七月 12, 2020 6:23:14 下午 com.alibaba.druid.pool.DruidDataSource info
信息: {dataSource-1} inited
密码是 123
Process finished with exit code 0