【问题标题】:JDBC sql server: set IDENTITY_INSERT ON: no effectJDBC sql server:设置 IDENTITY_INSERT ON:无效
【发布时间】:2020-09-08 02:17:46
【问题描述】:

JDBC sql server:设置 IDENTITY_INSERT ON:无效。

PreparedStatement stmt = connection.prepareStatement("SET IDENTITY_INSERT Table_FOO ON");
stmt.execute();
stmt.close();


PreparedStatement stmt2 = connection.prepareStatement("insert into Table_FOO (id, name) values (100, 'abc')");
stmt2.execute();
stmt2.close();

错误:仍然抱怨 DENTITY_INSERT 处于关闭状态。

com.microsoft.sqlserver.jdbc.SQLServerException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“Table_FOO”中插入标识列的显式值。

【问题讨论】:

    标签: sql-server jdbc identity-insert


    【解决方案1】:

    您可以尝试将语句组合成 1 个字符串并用分号终止语句

    PreparedStatement stmt = connection.prepareStatement("SET IDENTITY_INSERT Table_FOO ON; " +
                                                         "insert into Table_FOO (id, name) values (100, 'abc');" +
                                                         "SET IDENTITY_INSERT Table_FOO OFF;");
    stmt.execute();
    stmt.close();
    

    【讨论】:

    • 我会试试这个。不知道为什么这两个语句不起作用。谢谢。
    • @Sunnyday,驱动程序使用sp_executesql 执行准备好的语句,因此SET IDENTITY_INSERT ON 在语句执行后超出范围,恢复为OFF。恕我直言,最好的方法是像 SteveC 建议的那样将所有内容都包含在同一批次中。另一种方法是使用Statement 而不是PrepartedStatement 来表示SET IDENTITY_INSERT ON;。这将作为临时批处理执行查询并避免错误,因为后续的 PreparedStatement 位于内部范围内。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    相关资源
    最近更新 更多