sqlserver 数据库identity_insert问题

时间:2020-07-22 20:15:07   收藏:0   阅读:91

例如: 

@Test
 public void test() {
    String sql1 = "insert into emp values(null,?,?,?)"; //?占位符
    jdbcTemplate.update(sql1,"李四",24,"男");
 }

报错:Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: 仅当使用了列列表并且 IDENTITY_INSERT 为 ON 时,才能为表‘emp‘中的标识列指定显式值。

这是因为主键设置自增后,不能在sql语句中加入主键的值

正确写法:    String sql1 = "insert into emp values(?,?,?)"; //?占位符
    jdbcTemplate.update(sql1,"李四",24,"男");

或jdbcTemplate.update( "insert into emp values(‘凌子‘,21,‘女‘)");

另附identity_insert为on的写法(可以在自增主键下插入指定的主键 比如上一个是1而这个我需要5):
jdbcTemplate.update("set identity_insert emp on "
      + "insert into emp(eid,ename,age,sex) values(5,‘凌子‘,21,‘女‘) "
      + "set identity_insert emp off");

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!