一、定义工具类
(1)定义一个类 JDBCUtils
(2)提供静态代码块加载配置文件,初始化连接池对象
(3)提供方法
* 获取连接方法:通过数据库连接池获取连接
* 释放资源
* 获取连接池的方法
public class JDBCUtils {
private static DataSource ds ;
static{
try {
Properties pro = new Properties();
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void close(Statement stmt,Connection conn){
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(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 DataSource getDataSource(){
return ds;
}
}
二、使用工具类
public class DruidDemo {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JDBCUtils.getConnection();
String sql = "insert into account values(null,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,"王五");
pstmt.setDouble(2,3000);
int count = pstmt.executeUpdate();
System.out.println(count);
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(pstmt,conn);
}
}
}