JDBCUtils.java

    1. import java.io.FileReader;
    2. import java.io.IOException;
    3. import java.net.URL;
    4. import java.sql.*;
    5. import java.util.Properties;
    6. /**
    7. * JDBC工具类 8.0jar包版本
    8. */
    9. public class JDBCUtils {
    10. private static String url;
    11. private static String user;
    12. private static String password;
    13. /**
    14. * 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
    15. */
    16. static {
    17. //读取资源文件,获取值。
    18. try {
    19. //1. 创建Properties集合类。
    20. Properties pro = new Properties();
    21. //获取src路径下的文件的方式--->ClassLoader 类加载器
    22. ClassLoader classLoader = JDBCUtils.class.getClassLoader();
    23. URL res = classLoader.getResource("jdbc.properties");
    24. // assert res != null;
    25. String path = res.getPath();
    26. //2. 加载文件
    27. pro.load(new FileReader(path));
    28. //3. 获取数据,赋值
    29. url = pro.getProperty("url");
    30. user = pro.getProperty("user");
    31. password = pro.getProperty("password");
    32. String driver = pro.getProperty("driver");
    33. //4. 注册驱动
    34. Class.forName(driver);
    35. } catch (IOException e) {
    36. e.printStackTrace();
    37. } catch (ClassNotFoundException e) {
    38. e.printStackTrace();
    39. }
    40. }
    41. /**
    42. * 获取连接
    43. *
    44. * @return 连接对象
    45. */
    46. public static Connection getConnection(String dataBaseName) throws SQLException {
    47. String[] urlElem = url.split("\\?");
    48. return DriverManager.getConnection(urlElem[0] + dataBaseName + "?" + urlElem[1], user, password);
    49. }
    50. /**
    51. * 释放资源
    52. *
    53. * @param stmt
    54. * @param conn
    55. */
    56. public static void close(Statement stmt, Connection conn) {
    57. if (stmt != null) {
    58. try {
    59. stmt.close();
    60. } catch (SQLException e) {
    61. e.printStackTrace();
    62. }
    63. }
    64. if (conn != null) {
    65. try {
    66. conn.close();
    67. } catch (SQLException e) {
    68. e.printStackTrace();
    69. }
    70. }
    71. }
    72. /**
    73. * 释放资源
    74. *
    75. * @param stmt
    76. * @param conn
    77. */
    78. public static void close(ResultSet rs, Statement stmt, Connection conn) {
    79. if (rs != null) {
    80. try {
    81. rs.close();
    82. } catch (SQLException e) {
    83. e.printStackTrace();
    84. }
    85. }
    86. if (stmt != null) {
    87. try {
    88. stmt.close();
    89. } catch (SQLException e) {
    90. e.printStackTrace();
    91. }
    92. }
    93. if (conn != null) {
    94. try {
    95. conn.close();
    96. } catch (SQLException e) {
    97. e.printStackTrace();
    98. }
    99. }
    100. }
    101. }

    jdbc.properties

    1. driver=com.mysql.cj.jdbc.Driver
    2. user=root
    3. password=317499
    4. url=jdbc:mysql://127.0.0.1:3306/?Encoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true