[英]java sql error column is of type integer but expression is of type character varying
I have prepared sql statement: 我已经准备好sql语句:
PreparedStatement insert_query = db.prepareStatement(String.format(INSERT_QUERY, table,
columns.toString(), placeholder));
System.out.println(insert_query);
Result: 结果:
INSERT INTO "article" (article_text, article_id, article_title) VALUES (?, ?, ?) RETURNING article_id
Next I create values list, set parameters and execure insert query: 接下来,我创建值列表,设置参数并执行插入查询:
ArrayList<String> values = new ArrayList<String>(); -- > is [New CONTENT, 4, New TITLE]
for (int i = 1; i <= values.size(); i++) {
insert_query.setString(i, values.get(i-1));
}
System.out.println(insert_query);
insert_query.executeUpdate();
I got an error: 我收到一个错误:
INSERT INTO "article" (article_text, article_id, article_title) VALUES ('New CONTENT', '4', 'New TITLE') RETURNING article_id
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: column "article_id" is of type integer but expression is of type character varying
Something is wrong with article_id. article_id出了点问题。 I put it as string here. 我把它放在这里作为字符串。 However when I manually try this query in PostgreSQL everything works((( 但是,当我在PostgreSQL中手动尝试此查询时,一切正常(((
For the article_id, you must do insert_query.setInteger
instead of insert_query.setString
. 对于article_id,您必须执行insert_query.setInteger
而不是insert_query.setString
。 When I check your exception, the article_id is sent to the DB as a String. 当我检查您的异常时,article_id将作为字符串发送到数据库。 That's why you have this exception. 这就是为什么您有此异常。
Better solution I found is initiate values list as: 我发现更好的解决方案是初始化值列表为:
ArrayList<Object> values = new ArrayList<Object>();
And insert into statement object: 并插入语句对象:
insert_query.setObject(i, values.get(i-1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.