Java Postgresql更新JDBC

Java Postgresql更新JDBC,java,postgresql,jdbc,Java,Postgresql,Jdbc,我要更新表: id integer NOT NULL, "first" character varying(255), "last" character varying(255), age integer, CONSTRAINT registration_pkey PRIMARY KEY (id) 使用方法: void updateTable(String tableName, String columnName, String value, String column

我要更新表:

id integer NOT NULL,
"first" character varying(255),
"last" character varying(255),
age integer,
CONSTRAINT registration_pkey PRIMARY KEY (id)
使用方法:

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

}
如果我跑

.updateTable("employees", "last", "11", "id", "100");
一切都很好,但如果我尝试

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

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

您能告诉我问题出在哪里吗?

您不应该通过字符串连接直接放置变量来构建SQL。这里发生的是,使用11,您的SQL变成:

 set last=11
它是有效的SQL(使用11作为整数文本),而对于xx,它变成:

set last=xx
没有引号,因此SQL表示您正在读取另一列的值,因此显示错误消息。
由于您的值是一个字符串(进入varchar字段),因此需要将其用引号括起来。

在将sql字符串传递到execute update之前,可以尝试注销该字符串,以确保所有内容都按照您期望的方式进行。您给出的内容看起来不错,但在尝试执行时,将value2放在列名位置。。