Reputation: 1178
I have prepared sql statement:
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. I put it as string here. However when I manually try this query in PostgreSQL everything works(((
Upvotes: 4
Views: 11043
Reputation: 1178
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));
Upvotes: 2
Reputation: 5168
For the article_id, you must do insert_query.setInteger
instead of insert_query.setString
. When I check your exception, the article_id is sent to the DB as a String. That's why you have this exception.
Upvotes: 4