此方法很爛,以後優化
/** * 通用的查詢方法:SELECT */ @SuppressWarnings({ "unchecked", "rawtypes" }) public List testResultSet(String sql) { Connection connection = null; Statement statement = null; ResultSet rs = null; try { // 1.獲取Connection connection = JDBCTools.getConnection(); // 2.獲取Statement statement = connection.createStatement(); // 4.執行查詢,得到ResultSet rs = statement.executeQuery(sql); // 5.處理ResultSet List list = new ArrayList(); ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); while (rs.next()) { Map rowData = new HashMap(); for (int i = 1; i < columnCount; i++) { rowData.put(metaData.getColumnName(i), rs.getObject(i)); } list.add(rowData); } for (int i = 0;i < list.size();i++) { System.out.print(list.get(i)); System.out.println(); } return list; } catch (Exception e) { e.printStackTrace(); return null; } finally { // 6.關閉數據庫相應的資源 JDBCTools.release(rs, statement, connection); } }
為了方便看結果對不對,我給打印到控制台了,實際中可以沒有這個
懶得寫測試方法