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 121
| import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List;
public class JdbcGetAll {
public List getAll(String tableName, String className, Connection conn) { Class thisClass;
Field[] thisFields;
HashMap<String, Field> thisFieldsMap = new HashMap<>();
Constructor thisConstructor = null;
var COLUMN_NAMEs = new ArrayList<String>();
var thisInstances = new ArrayList();
try { thisClass = Class.forName(className); thisConstructor = thisClass.getConstructor(); thisFields = thisClass.getFields();
for (var field : thisFields) { thisFieldsMap.put(field.getName(), field); }
} catch (ClassNotFoundException e) { System.out.println("No class called '" + className + "'"); return null; } catch (NoSuchMethodException e) { e.printStackTrace(); }
var sql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = '" + tableName + "'";
PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { var COLUMN_NAME = rs.getString("COLUMN_NAME"); COLUMN_NAMEs.add(COLUMN_NAME); } } catch (SQLException e) { e.printStackTrace(); }
sql = "select * from " + tableName;
try { pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery();
while (rs.next()) { try { var thisInstance = thisConstructor.newInstance();
for (var COLUMN_NAME : COLUMN_NAMEs) {
var field = thisFieldsMap.get(COLUMN_NAME);
var o = rs.getObject(COLUMN_NAME);
field.set(thisInstance, o); } thisInstances.add(thisInstance); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } catch (SQLException e) { e.printStackTrace(); } finally { JdbcUitl.close(pstmt, conn); }
return thisInstances; }
public static void main(String[] args) { Connection conn = JdbcUitl.getConnection("address", 3306, "dbName", "root", "password"); var jdbcGetAll = new JdbcGetAll(); List res = jdbcGetAll.getAll("teacher", "Teacher", conn); System.out.println("结果集中共含有" + res.size() + "个元素: {"); for (var re : res) { System.out.println(" " + re); } System.out.println("}"); } }
|