Encapsulate query results as map using result set metadata

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.