package org.test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.local.jdbc.JdbcUtilSingle; public class ParameterMetaData { /** * 通过元数据获得字段信息,以Map类型返回List * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Object[] params = new Object[]{1}; List<Map<String,Object>> datas = read("select id,name from user where id<5"); System.out.println(datas); } public static List<Map<String,Object>> read(String sql){ Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; List<Map<String,Object>> datas = null; try{ conn = JdbcUtilSingle.getInstance().getConnection(); ps = conn.prepareStatement(sql); rs = ps.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData();//元数据信息 int count = rsmd.getColumnCount();//字段数量 String[] colNames = new String[count]; for(int i=1; i<=count; i++){ colNames[i-1] = rsmd.getColumnName(i);//字段名称 } datas = new ArrayList<Map<String,Object>>(); while(rs.next()){ Map<String, Object> item = new HashMap<String, Object>(); for(int i=1;i<=count;i++){ item.put(colNames[i-1], rs.getObject(colNames[i-1])); } datas.add(item); } }catch(SQLException e){ System.out.println(e.getMessage()); } return datas; } }