java 连接数据库mysql 以你之姓@ 2022-06-08 02:20 79阅读 0赞 连接数据库 @class: DbConnect public class DbConnect \{ public static Connection getconn() \{ Connection conn = null; String user = "root";//用户名 String passwd = "12345678";//密码 String url = "jdbc:mysql:localhost:3306/数据库名字"; //已加载完驱动 try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url,user,passwd); }catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return conn; } ## \} ## 关闭数据库 @DbClose public class DbClose \{ /** * 关闭 添加功能 资源 * @param pstmt,rs,conn */ public static void addClose(PreparedStatement pstmt, Connection conn) { /* * 多个 try-catch 出发点:安全 */ try { if (pstmt != null) { pstmt.close(); } } catch (SQLException e1) { e1.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭资源 * @param pstmt,rs,conn */ public static void queryClose(PreparedStatement pstmt, ResultSet rs, Connection conn) { try { if (pstmt != null) { pstmt.close(); } } catch (SQLException e1) { e1.printStackTrace(); } try { if (rs != null ) { rs.close(); } } catch (SQLException e1) { e1.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } ## \} ##
还没有评论,来说两句吧...