说明:

当前的工具类与配置文件都存放在src目录下


代码:

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DbUtils {
private static Properties properties = new Properties();

static {
try {
// 字节输入流获取
InputStream resourceAsStream = DbUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
// 集合加载数据
properties.load(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
}
// 驱动地址
String path = properties.getProperty("path");
// 加载驱动
try {
Class.forName(path);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

// 获得连接的方法
public static Connection getConnection() {
// 获取连接
// 连接heighschool库
String url = properties.getProperty("url");
// 用户名
String user = properties.getProperty("user");
// 密码
String password = properties.getProperty("password");
// 连接获得
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}

// 返回连接
return connection;
}

// 关闭连接的方法
public static void close(Connection connection, Statement statement, ResultSet resultSet) {
// 由小到大的关
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}

}