2011-12-21 85 views
0

我有一個查詢,它返回一個包含四個整數列的單個行。通過jdbctemplate運行查詢

select col1, col2, col3, col4 from myTable where id='xyz'; 

我應該從JdbcTemplate類以及如何使用哪一種查詢方式,使這些值在四個整形變量說INT1,INT2,INT3,INT4?

下面給出的rowMapper答案在我的情況下可能不起作用。因爲我沒有一個具有四個int屬性的對象,我可以設置它。

我正在一個方法中運行一個獨立的查詢,我想將返回的四列結果設置爲四個整數,這四個整數是該方法的局部變量。

我想知道,這是通過JdbcTemplate實現的?

以下代碼有效嗎?

List<String> result = this.jdbcTemplate.queryForObject(myQuery, List.class); 

Iterator i = result.iterator(); 

String a = (String) i.next(); 
String b = (String) i.next(); 
String c = (String) i.next(); 
String d = (String) i.next(); 
+1

你能否提出合理的降低投票的理由?僅僅因爲它的一個簡單問題並不意味着所有人都知道!如果其重複,請提供另一個問題的鏈接。如果不是 - 那麼它是一個有效的查詢。爲什麼downvote? – Nik 2011-12-21 12:37:40

+0

請看我更新的答案。 – flash 2011-12-21 14:51:04

回答

0

你可以使用一個queryForObject和使用的RowMapper行映射到你的對象。檢查樣品here

要將結果映射到局部變量,請使用queryForList(String sql)。請參見示例here。你會得到一個Object數組的列表,你可以從這個數組中提取值給你的變量。

+0

請看我更新的問題! – Nik 2011-12-21 12:48:09

+0

看到我編輯的答案 – 2011-12-21 13:42:55

0

你看過documentation

有一些很好的例子。看看query()方法和RowMapper類。

下面是一個簡單的例子:

//execute query 
List<MyEntity> entityList = jdbcTemplate.query(myQuery, new MyRowMapper()); 

//myEntity is a representation of the rows in the table 
    for (MyEntity myEntity : entityList) { 
     int a = myEntity.getA(); 
     int b = ... 
     //other getters 
    } 

class MyEntity { 
    private int a; 
    private int b; 
    private int c; 
    private int d; 

    public void setA(int a) { 
     this.a = a; 
    } 
    public int getA() { 
     return a; 
    } 

    //other getters & setters 
} 

class MyRowMapper implements RowMapper<MyEntity> { 

    @Override 
    public MyEntity mapRow(ResultSet rs, int rowNum) throws SQLException { 
     MyEntity myEntity = new MyEntity(); 
     myEntity.setA(rs.getInt(0)); 
     myEntity.setB(rs.getInt(1)); 
     myEntity.setC(rs.getInt(2)); 
     myEntity.setD(rs.getInt(3)); 
     return myEntity; 
    } 
} 
+0

請看我更新的問題!我不知道rowmapper如何幫助我! – Nik 2011-12-21 12:47:53