此方法很烂,以后优化
/** * 通用的查询方法: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); } }
为了方便看结果对不对,我给打印到控制台了,实际中可以没有这个
懒得写测试方法