List<Map> result = new ArrayList<Map>(); Connection conn = null; PreparedStatement pstmt; ResultSet rs; try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e){ System.out.println("驱动出错"); e.printStackTrace(); } try { conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:HelloWorld", "root", "root"); pstmt = conn.prepareStatement("select * from HelloWorld"); rs = pstmt.executeQuery(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); while (rs.next()) { Map map = new HashMap(); for (int i = 1; i <= columnCount; i++) { map.put(md.getColumnName(i), rs.getObject(i)); } result.add(map); } } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } //pstmt.close(); //rs.close(); }
finally中,conn的关闭必须放在第一个,而pstmt和rs是否有必要close()视具体情况而定。