2013-04-25 65 views
2

我正在使用Postgresql和Mysql的自動增量等效的SERIAL。我的表結構如下:JDBC如何在自動增加字段中插入記錄

id | name | description 

如何插入新記錄與結果集的工作(actualy CachedRowSet的,但它是相似的)?我試過這個:

rs.moveToInsertRow(); 
rs.updateString("name", "x"); 
rs.updateString("description", "xxx"); 
rs.insertRow(); 
rs.moveToCurrentRow(); 

但它不起作用。我得到一個執行。這是因爲我沒有指定id列的值。但我怎樣才能指定它?沒有任何選項可以讓JDBC自動插入它嗎?或者在插入記錄之前以某種方式檢索生成的密鑰?

回答

2

要創建一個更新的結果集,您必須指定在選擇選擇列表中的主鍵:

// Create a statement that will return updatable result sets 
    Statement stmt = connection.createStatement(
       ResultSet.TYPE_SCROLL_SENSITIVE, 
       ResultSet.CONCUR_UPDATABLE); 

    //Primary key/auto-increment 'id' must be specified 
    //so that the result set is updatable 
    ResultSet rs = stmt.executeQuery(
       "SELECT id, name, description FROM yourtable"); 
+0

但我希望只使用CachedRowSet的類。 ResultSet將始終保持連接處於活動狀態,這會浪費資源。請給我解決方案使用CachedRowSet。 – user2250795 2013-04-26 08:33:37

相關問題