1

这是我的代码:

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

此错误的原因和解决方案可能是什么。请帮忙。谢谢。

4

2 回答 2

6

不要在 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());

这段代码似乎可以工作,因为无论触发器是否已经存在,我都可以毫无错误地运行这段代码。如果触发器以前不存在,则创建它。

于 2012-08-10T10:48:23.530 回答
1

原因是因为“分隔符”不是mysql标准的一部分,只需删除分隔符语句,您的代码就可以工作。

于 2012-10-23T14:00:06.593 回答