这是我的代码:
triggerBuilder.append("DROP TRIGGER IF EXISTS `insert_associated_inquiry`; ");
triggerBuilder.append(" DELIMITER %% ");
triggerBuilder.append(" CREATE TRIGGER insert_associated_inquiry BEFORE UPDATE ON inquiry ");
triggerBuilder.append(" FOR EACH ROW Begin ");
triggerBuilder.append(" insert into associated_inquiries(inquiry_id , subject , content , inquiry_date , preferred_date ) " );
triggerBuilder.append("values");
triggerBuilder.append(" ( " );
triggerBuilder.append(" OLD.id , ");
triggerBuilder.append(" OLD.subject , " );
triggerBuilder.append(" OLD.content , " );
triggerBuilder.append(" OLD.created_on , " );
triggerBuilder.append(" OLD.preffered_date " );
triggerBuilder.append(" ) ; ");
triggerBuilder.append(" END %% ");
triggerBuilder.append(" DELIMITER ; ");
con.createStatement().execute(triggerBuilder.toString());
这就是抛出的错误:
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 'DELIMITER %% CREATE TRIGGER insert_associated_inquiry
BEFORE UPDATE ON inquiry ' at line 1
这个错误的原因和解决方案可能是什么。 求助。谢谢。
答案 0 :(得分:5)
不要在JDBC和MySQL中使用分隔符。分隔符仅由MySQL控制台使用,以便它可以判断您输入的触发器,存储过程等何时结束。在JDBC中,将整个SQL字符串放在一起,然后将其发送到数据库。因为您可以控制SQL何时被发送到数据库,所以不需要使用分隔符。
我从代码中删除了两个DELIMITER
行并使用了%%
分隔符,并将DROP TRIGGER
命令分别发送到数据库。我留下的代码如下:
con.createStatement().execute("DROP TRIGGER IF EXISTS `insert_associated_inquiry`");
triggerBuilder.append(" CREATE TRIGGER insert_associated_inquiry BEFORE UPDATE ON inquiry ");
triggerBuilder.append(" FOR EACH ROW Begin ");
triggerBuilder.append(" insert into associated_inquiries(inquiry_id , subject , content , inquiry_date , preferred_date ) " );
triggerBuilder.append("values");
triggerBuilder.append(" ( " );
triggerBuilder.append(" OLD.id , ");
triggerBuilder.append(" OLD.subject , " );
triggerBuilder.append(" OLD.content , " );
triggerBuilder.append(" OLD.created_on , " );
triggerBuilder.append(" OLD.preffered_date " );
triggerBuilder.append(" ) ; ");
triggerBuilder.append(" END ");
con.createStatement().execute(triggerBuilder.toString());
此代码似乎有效,因为无论触发器是否已存在,我都可以无错误地运行此代码。如果先前没有触发器,则会创建它。
答案 1 :(得分:1)
原因是因为“分隔符”不是mysql标准的一部分,只需删除分隔符并且你的代码应该可以工作。