如何透過JDBC到MySQL資料庫取得PreparedStatement的ResultSet的結果集,並且將每一筆結果集記錄逐一的轉存為List型態的資料集合,我們提供一個DBHelper類別的getDataModel的方法,它主要的作用就是要把ResultSet轉換為TreeMap,最後再把它一一的存到List集合裏面。
獲取Data Model的方法 (DBHelper.getDataModel)
將從資料庫獲取來的PreparedStatement物件導引至getDataModel函式,然後經由函式內部的邏輯處理之後,返回放置TreeMap型態的List集合物件
package jcode.test.db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public class DBHelper {
public DBHelper(){ }
public static List<TreeMap> getDataModel(PreparedStatement ps)
throws SQLException {
List rst = new ArrayList();
try {
ResultSet rs = ps.executeQuery();
while(rs.next()){
ResultSetMetaData rsmd = rs.getMetaData();
TreeMap map = processResultSet(rsmd, rs);
rst.add(map);
}
} catch (SQLException se) {
rst = null;
throw se;
}
return rst;
}
private static TreeMap processResultSet(ResultSetMetaData rsmd,
ResultSet rs) throws SQLException {
TreeMap tmp = new TreeMap();
try {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String columnName = rsmd.getColumnName(i).toUpperCase();
if (rsmd.getColumnType(i) == 1 ||
rsmd.getColumnType(i) == 12) {
if (rs.getString(i) == null) {
tmp.put(columnName, "");
} else {
tmp.put(columnName, rs.getString(i));
}
} else if (rsmd.getColumnType(i) == 93
|| rsmd.getColumnType(i) == java.sql.Types.DATE) {
tmp.put(columnName, rs.getTimestamp(i));
} else if (rsmd.getColumnType(i) == java.sql.Types.CLOB) {
if (rs.getClob(i) != null) {
tmp.put(columnName,rs.getClob(i).getSubString(1,
(int) rs.getClob(i).length()));
} else {
tmp.put(columnName, "");
}
} else {
tmp.put(columnName, rs.getBigDecimal(i));
}
}
} catch (SQLException sex) {
tmp = null;
throw sex;
}
return tmp;
}
}
|
DBTest測試代碼
- 以JDBC連結到MySQL的test schema
- 輸入查詢SQL "select * from test.user_info",返回
PreparedStatement型態的ps物件
- 把ps物件引入到DBHelper.getDataModel方法中,回傳List<TreeMap>型態的list物件
- 最後產出"總記錄數: XXX"的訊息到畫面上
package jcode.test.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.TreeMap;
public class DBTest {
/**
* @param args
*/
public static void main(String[] args) {
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=Big5");
String sql = "select * from test.user_info;";
PreparedStatement ps = con.prepareStatement(sql);
List<TreeMap> list = DBHelper.getDataModel(ps);
if(list != null){
System.out.println("總筆數: "+list.size());
}
}catch(ClassNotFoundException cfe){
cfe.printStackTrace();
}catch(SQLException se){
se.printStackTrace();
}finally{
try{
if(con != null) con.close();
}catch(SQLException ignore){ }
}
}
}
|
沒有留言:
張貼留言