封装为Utils类+程序资源文件去配置
public class Utils { static Properties p=null; static { p=new Properties(); try { p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties")); } catch (IOException e1) { e1.printStackTrace(); } try { Class.forName(p.getProperty("mysqlDriver")); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConn() { try { return DriverManager.getConnection(p.getProperty("mysqlURL") ,p.getProperty("mysqlUser"),p.getProperty("mysqlpwd")); } catch (SQLException e) { e.printStackTrace(); } return null; } public static void close(Connection conn) { try { if(conn!=null) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void close(PreparedStatement ps) { try { if(ps!=null) ps.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void close(ResultSet rs) { try { if(rs!=null) rs.close(); } catch (SQLException e) { e.printStackTrace(); } } public static void close(Connection conn,PreparedStatement ps,ResultSet rs) { close(conn); close(ps); close(rs); } }
资源文件如下db.properties
mysqlDriver=com.mysql.cj.jdbc.Driver mysqlURL=jdbc:mysql://localhost:3306/testjdbc?&useSSL=false&serverTimezone=UTC mysqlUser=root mysqlpwd=123456
如果需要调整,只需要更改配置文件中的相关信息
原文:https://www.cnblogs.com/code-fun/p/11443775.html