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 resultsetest est {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.exe cutequery (); 30 31 resultsetmetadata rsmd = Rs. getmetadata (); 32 33 // get the number of 34 int COUNT = rsmd columns. 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
Encapsulate query results as map using result set metadata