jdbc中自定义封装JDBCUntils类
封装的工具类
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
//封装jdbc工具类
public class JDBCUntils {
private static String url;
private static String user;
private static String password;
private static String driver;
//读取配置文件
static {
Properties properties = new Properties();
ClassLoader classLoader = JDBCUntils.class.getClassLoader();
InputStream stream = classLoader.getResourceAsStream("jdbc.properties");
try {
properties.load(stream);
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
driver = properties.getProperty("driver");
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取Connection对象
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
//释放资源
public static void close(Connection connection, Statement statement){
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//重载个释放资源的方法
public static void close(Connection connection, Statement statement, ResultSet resultSet){
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
jdbc.properties文件
url = 数据库地址
user = 用户名
password = 密码
driver = com.mysql.jdbc.Driver