JDBC工具类
目的:简化代码书写
实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.sql.*; import java.util.Properties;
public class JDBCUtils { private static String url; private static String user; private static String password; private static String driver;
static { try { Properties properties = new Properties(); ClassLoader classLoader = JDBCUtils.class.getClassLoader(); URL resource = classLoader.getResource("jdbc.properties"); String path = resource.getPath();
properties.load(new FileReader(path)); url = properties.getProperty("url"); user = properties.getProperty("user"); password = properties.getProperty("password"); driver = properties.getProperty("driver");
Class.forName(driver);
} catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }
}
public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,user,password); }
public static void close(Statement statement, Connection connection){
if (statement != null){ try { statement.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } }
if (connection != null){ try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } }
public static void close(ResultSet resultSet,Statement statement, Connection connection){
if (resultSet != null){ try { resultSet.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } }
if (statement != null){ try { statement.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } }
if (connection != null){ try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
|
创建配置文件:jdbc.properties
1 2 3 4
| url=jdbc:mysql:///test2?&useSSL=false&serverTimezone=UTC user=root password=1234 driver=com.mysql.cj.jdbc.Driver
|
在使用JDBC创建项目时就能使用工具类调用方法来代替大串的代码,并且改变数据库的连接只需要改动配置文件,不需要改动代码。