利用结果集元数据将查询结果封装为map

 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

 

转载于:https://www.cnblogs.com/aineko/p/3952501.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值