封装JDBCUtils工具类
直接配置连接参数的方式
创建JDBC的工具类
简化JDBC编程,工具类当中的方法都是静态的,不需要new对象直接采用类名调用
package com.bjpowernode.jdbc.utils;
import java.sql.*;
public class DBUtil {
// 工具类中的构造方法都是私有的可以防止new对象
private DBUtil() {
}
// 静态代码块在类加载时执行并且只执行一次
static {
try {
// 执行代码可能出现异常直接捕捉
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象
* @return 连接对象
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
// 执行这行代码可能会出现异常,将其抛出并在JDBC代码中捕捉
return DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode", "root", "333");
}
/**
* 关闭资源,由小到大,如果需要关闭哪个资源就传入对应的对象,不需要关闭就传入null
* @param conn 连接对象
* @param ps 数据库操作对象
* @param rs 结果集
*/
public static void close(Connection conn, Statement ps, ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
使用配置文件的方式
在实际开发中可以将编译异常转成运行异常
,这样调用者既可以选择捕获该异常也可以按照默认方式处理该异常
// 定义数据库连接信息的相关属性,因为只需要一份可以使用static修饰
private static String user; //用户名
private static String password; //密码
private static String url; //url
private static String driver; //驱动名
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
// 读取配置文件中的相关属性值
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driver = properties.getProperty("driver");
Class.forName(driver);
} catch (IOException e) {
//将编译异常转成运行异常
throw new RuntimeException(e);
}
}
// 连接数据库返回Connection对象
public static Connection getConnection() {
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// 将编译异常转成运行异常
throw new RuntimeException(e);
}
}
使用工具类后的基本骨架
public class JDBCTest12 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 获取连接
conn = DBUtil.getConnection();
// 获取预编译的数据库操作对象
} catch (Exception e) {
e.printStackTrace();
} finally{
// 释放资源
DBUtil.close(conn, ps, rs);
}
}
}