简体   繁体   中英

Postgresql Update JDBC

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM