如何为 JDBCPreparedStatement 设置 IDENTITY_INSERT 选项?
我需要将数据复制到具有标识列的 MSSQLServer 2005 数据库表中。
我已经了解了如何通过
SET IDENTITY_INSERT <table> ON
在插入查询之前执行来禁用标识列。
当我使用PreparedStatements进行批量插入并且在操作过程中无法更改语句时,我该如何做到这一点?
I need to copy data into an MSSQLServer 2005 database table which has an identity column.
I've seen how to disable the identity column by executing
SET IDENTITY_INSERT <table> ON
before the insert queries.
How can I do this when I'm using PreparedStatements to do batch inserts and I can't change the statement during the operation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
@Brabster 晚了几年,但它可能对任何需要做类似事情的人有用。 您可以使用传递给
prepareStatement()
的字符串中的串联语句来设置identity_insert
on
和off
:@Brabster A few years late, but it may be useful to anyone who needs to do something similar. You can set
identity_insert
on
andoff
with concatenated statements within the string you pass toprepareStatement()
:您可以将
SET IDENTITY_INSERT ON/OFF
包含在准备好的语句中。 这样,从客户端的角度来看,您只执行一个命令。You can include
SET IDENTITY_INSERT ON/OFF
as part of the prepared statement. This way you only execute one command from the perspective of the client.噢。 很简单,我想明白了。
首先创建一个Statement,执行SET IDENTITY_INSERT ON。 关闭声明。
创建PreparedStatement,执行批处理,关闭preparedstatement。
创建一个Statement,执行SET IDENTITY_INSERT OFF。 关闭并整理。
欢迎对此问题提出任何改进或建议...
D'oh. Easy, figured it out I think.
Create a Statement first, execute SET IDENTITY_INSERT ON. Close statement.
Create PreparedStatement, do batch stuff, close preparedstatement.
Create a Statement, execute SET IDENTITY_INSERT OFF. Close and tidy up.
Welcome any refinements or advice on issues with this...