JDBC - 通用增刪改查方式

 1     /**
 2      * Query the sql tool class of a single class.
 3      * @param sql sql
 4      * @param args args
 5      * @return class
 6      */
 7     public Tab getQuerySql(String sql, Object... args) {
 8         try (PreparedStatement ps = connection.prepareStatement(sql)) {
 9             for (int i = 0; i < args.length; i++) {
10                 ps.setObject(i + 1, args[i]);
11             }
12             // Get ResultSet
13             ResultSet resultSet = ps.executeQuery();
14             // Get the metadata of the result set
15             ResultSetMetaData metaData = resultSet.getMetaData();
16             // Get the number of columns
17             int columnCount = metaData.getColumnCount();
18             if (resultSet.next()) {
19                 Tab tab = new Tab();
20                 for (int i = 0; i < columnCount; i++) {
21                     // Get the column value of each column: through ResultSet
22                     Object columnValue = resultSet.getObject(i + 1);
23                     // Get the alias of the column through ResultSetMetaData
24                     String columnLabel = metaData.getColumnLabel(i + 1);
25                     // Through reflection, assign the specified name of the object columnLabel to the specified columnValue
26                     Field field = Tab.class.getDeclaredField(columnLabel);
27                     field.setAccessible(true);
28                     field.set(tab, columnValue);
29                 }
30                 return tab;
31             }
32         } catch (Exception throwables) {
33             throwables.printStackTrace();
34         }
35         return null;
36     }
37 
38     /**
39      * Add, delete, modify and check a single class.
40      * @param sql sql 
41      * @param args args
42      * @return boolean
43      */
44     public boolean executeSql(String sql, Object... args) {
45         try (PreparedStatement ps = connection.prepareStatement(sql)) {
46             for (int i = 0; i < args.length; i++) {
47                 ps.setObject(i + 1, args[i]);
48             }
49             return ps.execute();
50         } catch (Exception throwables) {
51             throwables.printStackTrace();
52         }
53         return false;
54     }

 

JDBC - 通用增刪改查方式

上一篇:MongoDB操作


下一篇:rpm安装Oracle19c