在 prepareStatementin java, sql 中转义圆括号和等号。

Escaping Round bracket and equal sign in prepareStatementin java, sql.

我正在尝试使用以下语句编写 sql 语句来切换数据库中 varchar(5) 列的值。

stmt = connection.prepareStatement("UPDATE  TABLENAME  SET
                + MIDNIGHT =IF\\(MIDNIGHT=?,?,?\\)");
stmt.setString(1, "off");
stmt.setString(2, "on");
stmt.setString(3, "off");

但我收到以下错误:

com.ibm.db2.jcc.am.SqlSyntaxErrorException:DB2 SQL 错误:SQLCODE=-7,SQLSTATE=42601,SQLERRMC =\;GHT =IF, DRIVER=3.59.81

MIDNIGHT 是我试图在 'on' 和 'off' 之间切换其值的列的名称。

我做错了什么?

SQL0007N - The character "" following "" is not valid.

Explanation:

The specified "" is not a valid character in SQL statements. The "" field indicates the 20 characters of the SQL statement that preceded the character that is not valid.

Federated system users: some data sources do not provide the appropriate values for the "" and "" message tokens. In these cases, "" and "" will have the following format: ":UNKNOWN", indicating that the actual values for the specified data source are unknown.

The statement cannot be processed.

User Response:

Remove or replace the character that is not valid.

sqlcode : -7

sqlstate : 42601

此外,在您的查询中,您不能像在Java中那样使用IF语句。

一个可能的解决方法是使用 case 语句。

update TABLENAME  SET MIDNIGHT =
case when MIDNIGHT = ? then ?
     when MIDNIGHT = ? then ?
end;