1

I want to update table:

id integer NOT NULL,
"first" character varying(255),
"last" character varying(255),
age integer,
CONSTRAINT registration_pkey PRIMARY KEY (id)

using method:

    void updateTable(String tableName, String columnName, String value,
        String columnName2, String value2) {
    try {

        String sql = "UPDATE " + tableName + " SET " + columnName + " = "
                + value + " WHERE " + columnName2 + " = " + value2;

        stmt.executeUpdate(sql);

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

If i run

.updateTable("employees", "last", "11", "id", "100");

everything is ok, but if i try

.updateTable("employees", "last", "xx", "id", "100");

i recieve

org.postgresql.util.PSQLException: ERROR: column "xx" does not exist
  Position: 29
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998).....

can you tell me, where is the problem?

1
  • 1
    Maybe try logging out your sql string before you pass it into execute update, just to make sure that everything is playing out the way you expect. What you've given seems fine, but when attempting to execute it with the value2 being placed into a column name position.. Commented Jun 22, 2015 at 14:53

1 Answer 1

1

You shouldn't build SQL by putting your variables directly via string concatenation. What happens here is that with 11, your SQL becomes:

 set last=11

Which is valid SQL (using 11 as a integer literal), while with xx it becomes:

set last=xx

There are no quotes, so the SQL means you're reading the value of another column, hence your error message. Since your value is a string (going into a varchar field), you need to wrap it in quotes.

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

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.