jdbc封装
package com.qfedu.Util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* 工具类能干嘛?
* 1.自动完成驱动的加载
* 2.自动完成必要的数据处理
* 3.简化getConnection方法,提供给开发者
* 4.完成统一的close方法
*/
public class JdbcUtil {
private static String url = null;
private static String user = null;
private static String password = null;
private static String driverClass = null;
static {
try {
//需要读取src下面的一个文件 db.properties
//1.创建一个properties对象
Properties properties = new Properties();
//2.使用load方法加载文件
properties.load(new FileInputStream("./src/db.properties"));
//3.从Properties对象获取连接数据的参数(url dirver user password)
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
driverClass = properties.getProperty("driver");
//4.加载驱动
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getConnection () {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* 关闭数据库连接对象
*/
//假如statement 是null resultSet是null
public static void close(Connection connection) {
try {
close(connection, null, null);
} catch (SQLException e) {
e.printStackTrace();
}
}
//resultSet是null
public static void close(Connection connection, Statement statement) {
try {
close(connection, statement, null);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (resultSet != null) {
resultSet.close();
}
}
}