我正在尝试使用“Spring MVC”项目将数据插入Microsoft服务器管理工作室表。
联系人ID已设为NOT NULL
和AUTO INCREMENT by 1
。即使它试图插入null。
我定义user id
主键不为null和identity 1.这是创建表的查询:
CREATE TABLE contact (
contact_id[int] IDENTITY(1,1) NOT NULL,
name varchar(45) NOT NULL,
email varchar(45) NOT NULL,
address varchar(45) NOT NULL,
telephone varchar(45) NOT NULL,
PRIMARY KEY (contact_id)
)
表设计:
错误:
SEVERE: Servlet.service() for servlet [SpringDispatcher] in context with path [/SpringMvcJdbcTemplate] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [INSERT INTO contact (name, email, address, telephone) VALUES (?, ?, ?, ?)]; Cannot insert the value NULL into column 'contact_id', table 'contactdb.dbo.contact'; column does not allow nulls. INSERT fails.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into column 'contact_id', table 'contactdb.dbo.contact'; column does not allow nulls. INSERT fails.] with root cause
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into column 'contact_id', table 'contactdb.dbo.contact'; column does not allow nulls. INSERT fails.
代码行:
//插入
String sql = "INSERT INTO contact (name, email, address, telephone)"
+ " VALUES ('" + contact.getName() + "', '" + contact.getEmail() + "', '" + contact.getAddress() + "', '" + contact.getTelephone() + "')";
jdbcTemplate.update(sql);
更新
CREATE TABLE contact (
contact_id int IDENTITY NOT NULL PRIMARY KEY,
name varchar(45) ,
email varchar(45) NOT NULL,
address varchar(45) NOT NULL,
telephone varchar(45) NOT NULL
)
答案 0 :(得分:0)
创建一个过程或在默认值中添加SCOPE_IDENTITY()方法。