2015-12-17 105 views
1

我想在查詢數據庫後從ResultSet中獲取值,所以我該如何執行。這是我的代碼的一些行從ResultSet Java中獲取值

conn = DBConnection.connect(); 
    String SQL = "SELECT * from usertable"; 
    // ResultSet 
    ResultSet rs = conn.createStatement().executeQuery(SQL); 
    if (rs.next()) { 
     System.out.println(rs.getString(1)); 
    } 

它打印:「1」,而不是我想要的值。有誰能幫我解決這個問題嗎?這是用戶表的示例數據:

Example data

+0

您想要閱讀哪一欄? –

+0

嘗試「獲取」不同的列。 「1」確實是第一列中的值是完全可能的。 –

+0

我想獲得所有列並將其返回給Person類型,如: Person person = rs.getSomething()。getFirstname(); –

回答

3

你不把你的問題的更多細節,但是這是一個例子:
你有這樣的人類字段,你可以通過自己

做二傳手消氣
class Person{ 
    String name; 
    int id; 
} 

然後在您的ResultSet:
覺得你的表有兩個列(「用戶id」和「名字」)和第一列是「用戶id」

PreparedStatement ps = null; 
    Connection con = null; 
    String SQL = "SELECT * from usertable LIMIT 1";// LIMIT 1 because you have one Person Object to fill otherwise you must be have an Array of Person 
    try { 
     con = DBConnection.getConnection(); 
     ps = con.prepareStatement(SQL); 
     ResultSet rs = ps.executeQuery(); 
     Person p=null; 
     while (rs.next()) { 
     p=new Person(); 
     p.id=rs.getInt(1); 
     // or p.id=rs.getInt("userid"); by name of column 
     p.name=rs.getString(2); 
     // or p.name=rs.getString("firstname"); by name of column    
     } 
    return p; 
    } catch (SQLException ex) { 
     Logger.getLogger(YourClassName.class.getName()).log(Level.SEVERE, null, ex); 
     return null; 
    } finally { 
     if (con != null) { 
      try { 
       con.close(); 
      } catch (SQLException ex) { 
       Logger.getLogger(YourClassName.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } 
     if (ps != null) { 
      try { 
       ps.close(); 
      } catch (SQLException ex) { 
       Logger.getLogger(YourClassName.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } 
    } 

如果您的結果不止一個,您必須更改Person to Person []或「ArrayList」對象

+0

這就是我想要的。謝謝 :) –