JDBC工具类的提取
package JDBCUtils; import java.sql.*; public class JDBCUtils{ private static final String driverClass; private static final String url; private static final String username; private static final String password; static{ driverClass="com.mysql.jdbc.Driver"; url="jdbc:mysql:///jdbc?serverTimezone=UTC"; username="root"; password="root";
try{
loadDriver();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
} public void loadDriver() throws ClassNotFoundException { Class.forName(driverClass); } public static Connection getConnection() throws SQLException { Connection conn = DriverManager.getConnection(url, username, password); return conn; } public static void release(Connection conn, Statement stat) { if (stat != null) { try { stat.close(); } catch (SQLException e) { e.printStackTrace(); } stat = null; } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } conn = null; } } public static void release(ResultSet rs,Connection conn, Statement stat) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } rs = null; } if (stat != null) { try { stat.close(); } catch (SQLException e) { e.printStackTrace(); } stat = null; } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } conn = null; } } }
try {
loadDriver();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步