0

在我的 java 项目中,我需要检查表中是否存在一行。如果存在,我需要更新;如果没有,我需要创建它。执行此操作的 Sql 语法应该是:

IF EXISTS(SELECT * FROM table1 WHERE column4='"+int4+"' AND column5='"+int5+"') "
                +"BEGIN "
+ "UPDATE table1"
+ "SET column1='"+int1+"', column2='"+int2+"' "
+ "WHERE column4='"+int4+"' and column5='"+int5+"' "
+ "END "
+ "ELSE"
+ "INSERT INTO table1 (column1, column2, column4, column5, column3) "
                + "VALUES ('" + int1 + "',"
                + "'" + int2 + "',"
                + "'" + int4 + "',"
                + "'" + int5 + "',"
                + "'" + int3 +"');

其中int1, int2, int3, int4, int5是整数值。好吧,如果我把这段代码放在我的 java 编译器上,我的 Sql 语法错误:

 com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM table1 WHERE column4='1' AND column5='0') BEGIN UPDATE' at line 1

但我看不到错误

4

1 回答 1

3

您遇到了一个错误,因为在 MySQL 中,您不能IF在存储例程(存储过程、存储函数、触发器)中使用条件语句。

您需要的是所谓UPSERT的,您可以在 MySQL 中使用INSERT INTO ... ON DUPLICATE KEY UPDATE. 为了让它工作,你必须有一个UNIQUE INDEXoncolumn4column5

ALTER TABLE table1 ADD UNIQUE (column4, column5);

现在你的INSERT陈述可能看起来像

INSERT INTO table1 (column1, column2, column4, column5, column3)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE column1=VALUES(column1), column2=VALUES(column2);

这是SQLFiddle演示

附带说明:使用参数化查询而不是插入查询字符串。我不是 Java 专家,但我确信它拥有一流的基础设施。否则,您对 SQL 注入持开放态度。

于 2013-09-24T12:04:50.850 回答