IF EXISTS语句中的语法SQL错误

时间:2013-09-24 11:50:20

标签: java mysql sql

在我的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

但我看不到错误

1 个答案:

答案 0 :(得分:3)

你有一个错误,因为在MySQL中你不能使用除存储例程(存储过程,存储函数,触发器)之外的条件语句IF

您需要的是所谓的UPSERT,您可以使用INSERT INTO ... ON DUPLICATE KEY UPDATE在MySQL中实现。要使其发挥作用,您必须在UNIQUE INDEXcolumn4上设置column5

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注入非常开放。

相关问题