先导入jia包
驱动jar包
druid的Jar包
写配置文件
定义配置文件(手动加载)
- 名称:自定义
- 路径:自定义
封装工具类代码
package com.lingaolu.dataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* @author 林高禄
* @create 2020-06-26-17:52
*/
public class JdbcUtils {
private static DataSource ds;
static{
try {
// 加载配置文件
Properties p = new Properties();
p.load(JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
// 获取DataSource对象
ds = DruidDataSourceFactory.createDataSource(p);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() throws SQLException {
if(ds == null){
return null;
}
return ds.getConnection();
}
// 释放资源
public static void close(Statement stmt,Connection con){
close(null,stmt,con);
}
// 释放资源
public static void close(ResultSet rs,Statement stmt,Connection con){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 获取连接池
public static DataSource getDataSource(){
return ds;
}
}
数据库数据
测试demo
package com.lingaolu.dataSource;
import java.sql.*;
/**
* @author 林高禄
* @create 2020-06-26-18:05
*/
public class DruidDemo {
public static void main(String[] args) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = JdbcUtils.getConnection();
String sql = "select * from Account where name=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1,"张三");
rs = pstmt.executeQuery();
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id+name);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.close(rs,pstmt,con);
}
}
}
运行输出:
1张三
7张三