一、UbUtil
package util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DbUtil {
private static String url = "";
private static String username = "";
private static String password = "";
public static void main(String[] args) {
System.out.println(getConnection());
}
//加载数据库的驱动类
static {
//获取配置文件字节输入流
InputStream in = DbUtil.class.getClassLoader().getResourceAsStream("db.properties");
//创建“键值对”集合对象
Properties properties = new Properties();
try {
//加载数据
properties.load(in);
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(properties.getProperty("driver"));
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
// 获取数据库的连接对象
public static Connection getConnection(){
Connection connection = null;
try {
//把数据硬编码在程序中,从配置文件中读取数据! config , init
connection = DriverManager.getConnection(url,username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
// 关闭资源
public static void closeAll(ResultSet rs, PreparedStatement ps, Connection conn) {
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();
}
}
}
}
对应的db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/school
username=root
password=root
记得要导入mysql的jar包