1. 程式人生 > 程式設計 >java中ResultSet遍歷資料操作

java中ResultSet遍歷資料操作

1.查詢資料庫中表的列名

<pre name="code" class="html">String sql = "select *from tblmetadatainfo";
 ResultSet rs = MySqlHelper.executeQuery(sql,null);
 String str="";
 try {
  ResultSetMetaData rsmd = rs.getMetaData();
  for (int i = 1; i < rsmd.getColumnCount(); i++) {
  str+=rsmd.getColumnName(i)+",";
  }
  str=str.substring(0,str.length()-1);
 } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

2.查詢資料庫中表中每條記錄的列值

for(int i=1;i<rs.getMetaData().getColumnCount();i++){
   str+=rs.getString(i)+",";
  }

補充知識:Java:使用ResultSet.next()執行含有rownum的SQL語句速度緩慢

在使用Oracle資料庫進行分頁查詢時,經常會用到如下SQL:

select tm.* from (select rownum rm,t.* xmlrecord from testtable t) tm where tm.rm > ? and tm.rm <= ?

使用的java程式碼如下:

int startIdx = 0;
int endIdx = 10000; 
String sql = "select tm.* from (select rownum rm,t.* xmlrecord from testtable t) tm where tm.rm > ? and tm.rm <= ?";
 
try (Connection conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql);) {
 
 ps.setInt(1,startIdx);
 ps.setInt(2,endIdx);
 
 try (ResultSet rs = ps.executeQuery();) {
 while (rs.next()) {
  String id = rs.getString(2);
 
  System.out.println("id="+id);
 }
 }
}

當使用以上程式碼時,會發現當取完最後一條記錄後,再執行rs.next()時,本來希望返回false後跳出迴圈,但rs.next()會執行非常長的時間。解決的方法是不讓rs.next()來判斷下一條記錄不存在,而在程式碼通過計數來實現:

int startIdx = 0;
int endIdx = 10000;
int i = 0;
int count = endIdx - startIdx;
String sql = "select tm.* from (select rownum rm,endIdx);
 
 try (ResultSet rs = ps.executeQuery();) {
  while (rs.next()) {
  i++;
  String id = rs.getString(2); 
  System.out.println("id="+id);
   if(i == count) {
   break;
  }
 }
 }
}

如果程式碼中設定了fetchSize,並且fetchSize不能被count整除時,在取最後一片資料時,rs.next()也會執行很長時間:

int startIdx = 0;
int endIdx = 10000; 
String sql = "select tm.* from (select rownum rm,t.* xmlrecord from testtable t) tm where tm.rm > ? and tm.rm <= ?";
 
try (Connection conn = dataSource.getConnection(); PreparedStatement ps = conn.prepareStatement(sql);) {
 ps.setFetchSize(300);
 ps.setInt(1,endIdx);
 
 try (ResultSet rs = ps.executeQuery();) {
 
 while (rs.next()) {
  String id = rs.getString(2);
 
  System.out.println("id="+id);
 }
 }
}

以上程式碼中,當取得9900條資料後,再取下一個300條時,rs.next()就會執行很長時間,可能是由於取不到一個完整的300條記錄造成的。解決方法是將fetchSize設定成能被count整除的數字,比如:

ps.setFetchSize(500);

在以上兩種狀況下,為什麼rs.next()會執行很長時間,還不是很清楚,但可以通過上述方式解決。至於為什麼會有這個問題,有知道原因的朋友,請不吝賜教。

以上這篇java中ResultSet遍歷資料操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。