将JDBC ResultSet结果集转成List
2017-07-27 本文已影响298人
九七学姐
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by xh on 17-7-26.
* 随机读取数据库中的size条记录,注意,tableName及记录的条数作为参数传入,所以需要用到字符串拼接,StringBuffer()
* append()方法,另外需要转换成字符串的时候使用.toString()即可
*/
public class ReadSqlrecorderRandom {
public static void main(String[] args) throws IOException {
getRecordsRandom("jdbc:mysql://localhost:3306/xyj","User",2);
}
public static List<Map<String,Object>> getRecordsRandom(String url, String tableName, int size) throws IOException {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
String user = "root";
String password = "123456";
List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
try {
con = DriverManager.getConnection(url, user, password);
StringBuffer sql=new StringBuffer("SELECT * FROM ");
if(tableName !=null){
sql.append(tableName);
sql.append(" order by rand() LIMIT ");
sql.append(size);
}
pst = con.prepareStatement(sql.toString());
rs = pst.executeQuery();
ResultSetMetaData md = rs.getMetaData(); //获得结果集结构信息,元数据
int columnCount = md.getColumnCount(); //获得列数
while (rs.next()) {
Map<String,Object> rowData = new HashMap<String,Object>();
for(int i = 1;i<=columnCount;i++){
rowData.put(md.getColumnName(i), rs.getObject(i));
}
//System.out.println(rowData);
list.add(rowData); //之前rowData在while外面,list.add()重复引用,指向同一块内存,所以值被覆盖,重复出现后面的值
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (rs != null) {rs.close();rs=null;}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
System.out.println(list);
return list;
}
}