当前位置:Gxlcms > 数据库问题 > sqlserver 数据库identity_insert问题

sqlserver 数据库identity_insert问题

时间:2021-07-01 10:21:17 帮助过:49人阅读

例如: 

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

 

sqlserver 数据库identity_insert问题

标签:serve   value   insert   需要   bsp   com   插入   template   jdbc   

人气教程排行