【问题标题】:JDBC how to insert record in auto-increment fieldJDBC如何在自增字段中插入记录
【发布时间】:2013-04-25 16:15:36
【问题描述】:

我正在使用 Postgresql 和 Mysql 的自动增量等效序列。我的表结构如下:

id | name | description

如何插入使用结果集的新记录(实际上是 CachedRowSet 但类似)?我试过这个:

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

但它不起作用。我得到一个例外。这是因为我没有指定 id 列值。但是我该如何指定呢?没有任何选项可以让 JDBC 自动插入它吗?或者在插入记录之前检索生成的键的某种方式?

【问题讨论】:

    标签: java jdbc


    【解决方案1】:

    要创建可更新的结果集,您必须在选择列表中指定主键:

        // 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");
    

    【讨论】:

    • 但我只想使用 CachedRowSet 类。 ResultSet 将一直保持连接活动,这将浪费资源。请给我使用 CachedRowSet 的解决方案。
    猜你喜欢
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多