1 package it.cast.jdbc; 2 3 import java.sql.Connection; 4 import java.sql.ParameterMetaData; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.ResultSetMetaData; 8 import java.sql.SQLException; 9 import java.util.HashMap; 10 import java.util.Map; 11 12 public class ResultSetMetaTest { 13 14 public static void main(String[] args) throws SQLException { 15 16 Map<String,Object> map = read("select * from user where id=2"); 17 System.out.println(map); 18 } 19 20 static Map<String, Object> read(String sql) throws SQLException { 21 22 Connection conn = null; 23 PreparedStatement ps = null; 24 ResultSet rs = null; 25 26 try { 27 conn = jdbcUtils.getConnection(); 28 ps = conn.prepareStatement(sql); 29 rs = ps.executeQuery(); 30 31 ResultSetMetaData rsmd = rs.getMetaData(); 32 33 // 得出有多少列 34 int count = rsmd.getColumnCount(); 35 36 String[] colNames = new String[count]; 37 38 for (int i = 1; i <= count; i++) { 39 // System.out.print(rsmd.getColumnClassName(i)+"\t"); 40 // System.out.print(rsmd.getColumnName(i)+"\t"); 41 // System.out.println(rsmd.getColumnLabel(i)+"\t"); 42 colNames[i-1] = rsmd.getColumnName(i); 43 } 44 45 Map<String, Object> data = null; 46 47 while (rs.next()) { 48 data = new HashMap<String, Object>(); 49 50 for (int j = 0; j < colNames.length; j++) { 51 data.put(colNames[j], rs.getObject(colNames[j])); 52 } 53 } 54 55 return data; 56 } finally { 57 jdbcUtils.free(rs, ps, conn); 58 } 59 } 60 }
ResultSetMetaTest
时间: 2025-01-02 14:20:48