数据库连接工具类——包含取得连接和关闭资源 ConnUtil.java

时间:2023-03-09 15:35:59
数据库连接工具类——包含取得连接和关闭资源 ConnUtil.java
  1. package com.util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. /**
  8. * @className: ConnUtil.java
  9. * @classDescription: 数据库连接工具类——包含取得连接和关闭资源
  10. * @function:
  11. * @author: Wentasy
  12. * @createTime: 2012-9-24 上午11:51:15
  13. * @modifyTime:
  14. * @modifyReason:
  15. * @since: JDK 1.6
  16. */
  17. public class ConnUtil {
  18. public static final String url = "jdbc:mysql://XXX.XXX.XXX.XXX:3306/dbadapter";
  19. public static final String user = "root";
  20. public static final String password = "XXXXXX";
  21. /**
  22. * 得到连接
  23. * @return
  24. * @throws SQLException
  25. * @throws ClassNotFoundException
  26. */
  27. public static Connection establishConn() throws SQLException,ClassNotFoundException{
  28. Class.forName("com.mysql.jdbc.Driver");
  29. return DriverManager.getConnection(url, user, password);
  30. }
  31. /**
  32. * 关闭连接
  33. * @param conn
  34. * @throws SQLException
  35. */
  36. public static void close(Connection conn) throws SQLException{
  37. if(conn != null){
  38. conn.close();
  39. conn = null;
  40. }
  41. }
  42. /**
  43. * 关闭PreparedStatement
  44. * @param pstmt
  45. * @throws SQLException
  46. */
  47. public static void close(PreparedStatement pstmt) throws SQLException{
  48. if(pstmt != null){
  49. pstmt.close();
  50. pstmt = null;
  51. }
  52. }
  53. /**
  54. * 关闭结果集
  55. * @param rs
  56. * @throws SQLException
  57. */
  58. public static void close(ResultSet rs) throws SQLException{
  59. if(rs != null){
  60. rs.close();
  61. rs = null;
  62. }
  63. }
  64. }