JDBCUtils.java
import java.io.FileReader;import java.io.IOException;import java.net.URL;import java.sql.*;import java.util.Properties;/*** JDBC工具类 8.0jar包版本*/public class JDBCUtils {private static String url;private static String user;private static String password;/*** 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块*/static {//读取资源文件,获取值。try {//1. 创建Properties集合类。Properties pro = new Properties();//获取src路径下的文件的方式--->ClassLoader 类加载器ClassLoader classLoader = JDBCUtils.class.getClassLoader();URL res = classLoader.getResource("jdbc.properties");// assert res != null;String path = res.getPath();//2. 加载文件pro.load(new FileReader(path));//3. 获取数据,赋值url = pro.getProperty("url");user = pro.getProperty("user");password = pro.getProperty("password");String driver = pro.getProperty("driver");//4. 注册驱动Class.forName(driver);} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();}}/*** 获取连接** @return 连接对象*/public static Connection getConnection(String dataBaseName) throws SQLException {String[] urlElem = url.split("\\?");return DriverManager.getConnection(urlElem[0] + dataBaseName + "?" + urlElem[1], user, password);}/*** 释放资源** @param stmt* @param conn*/public static void close(Statement stmt, Connection conn) {if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}/*** 释放资源** @param stmt* @param conn*/public static void close(ResultSet rs, Statement stmt, Connection conn) {if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}}
jdbc.properties
driver=com.mysql.cj.jdbc.Driveruser=rootpassword=317499url=jdbc:mysql://127.0.0.1:3306/?Encoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
