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

 package it.cast.jdbc;

 import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map; public class ResultSetMetaTest { public static void main(String[] args) throws SQLException { Map<String,Object> map = read("select * from user where id=2");
System.out.println(map);
} static Map<String, Object> read(String sql) throws SQLException { Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null; try {
conn = jdbcUtils.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++) {
// System.out.print(rsmd.getColumnClassName(i)+"\t");
// System.out.print(rsmd.getColumnName(i)+"\t");
// System.out.println(rsmd.getColumnLabel(i)+"\t");
colNames[i-1] = rsmd.getColumnName(i);
} Map<String, Object> data = null; while (rs.next()) {
data = new HashMap<String, Object>(); for (int j = 0; j < colNames.length; j++) {
data.put(colNames[j], rs.getObject(colNames[j]));
}
} return data;
} finally {
jdbcUtils.free(rs, ps, conn);
}
}
}

ResultSetMetaTest

上一篇:POJ2735/Gym 100650E Reliable Nets dfs


下一篇:Extjs4 页数重置