[英]PSQLException: ERROR: null value in column violates not-null constraint
I am using PostgreSQL 8.4.13 on x86_64-pc-linux-gnu on Debian 4.4.5-8, 64-bit.我在 64 位 Debian 4.4.5-8 上的 x86_64-pc-linux-gnu 上使用 PostgreSQL 8.4.13。
I have created the following table:我创建了下表:
CREATE TABLE users (
user_id serial PRIMARY KEY NOT NULL,
name varchar(200),
username varchar(150),
password varchar(150),
);
Then, using a Java application, I execute the following code:然后,使用 Java 应用程序,我执行以下代码:
String insertTableSQL = "INSERT INTO USERS"
+ "(name, username, password) VALUES"
+ "(?,?,?)";
PreparedStatement preparedStatement = DBCon.prepareStatement(insertTableSQL);
preparedStatement.setString(1, userInfo.get("name"));
preparedStatement.setString(2, userInfo.get("username"));
preparedStatement.setString(3, userInfo.get("password")));
preparedStatement.executeUpdate();
The issue here is that the executeUpdate() generates the following exception:这里的问题是 executeUpdate() 生成以下异常:
org.postgresql.util.PSQLException: ERROR: null value in column "user_id" violates not-null constraint
The weird thing is that if I execute the same insert statement using psql, it executes successfully.奇怪的是,如果我使用 psql 执行相同的插入语句,它会成功执行。
Any ideas would be much appreciated.任何想法将不胜感激。
Thank you.谢谢你。
As @mu commented, the error message contradicts the rest of your question.正如@mu 评论的那样,错误消息与您的其余问题相矛盾。
The only reasonable explanation left is that you are, in fact, writing to a different table剩下的唯一合理解释是,实际上,您正在写入不同的表
Try:尝试:
INSERT INTO users (user_id, name, username, password) VALUES
(1234,'foo', 'foo', 'foo')";
And check your table.并检查你的桌子。 Did the INSERT arrive at the table you expected?
INSERT 是否到达您预期的表? If not, check your settings:
如果没有,请检查您的设置:
search_path
setting.search_path
设置。 Find the other instance of table users
and fix potential damage you may have done.找到表
users
的其他实例并修复您可能造成的潜在损坏。 :) :)
String insertTableSQL = "INSERT INTO USERS"
+ "(name, username, password) VALUES"
+ "(?,?,?)";
PreparedStatement preparedStatement = DBCon.prepareStatement(insertTableSQL);
preparedStatement.setString(1, userInfo.get("name"));
preparedStatement.setString(2, userInfo.get("username"));
preparedStatement.setString(3, userInfo.get("password")));
preparedStatement.executeUpdate();
Note only three question marks and now the fields line up correctly.请注意仅三个问号,现在字段正确排列。
Also don't worry about the NOT NULL
constraint.也不要担心
NOT NULL
约束。 It will handle itself (how could it ever be NULL
, it's SERIAL
) and could be causing your error.它会自行处理(它怎么可能是
NULL
,它是SERIAL
)并且可能会导致您的错误。 Just remove it.只需将其删除。
Resolved.解决。
The problem with me was that I was having 2 column in the database and in entity there was one mapped.我的问题是我在数据库中有 2 列,而在实体中有一个映射。 it happened due to sql update in properties file
它是由于属性文件中的 sql 更新而发生的
once remove one and get fixed一旦删除并得到修复
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.