4

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(((

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.