delimiter
以下是从mysql官方文档《23.3.1 Trigger Syntax and Examples》抄来的一段创建触发器的SQL脚本,
代码语言:javascript复制delimiter //
CREATE TRIGGER upd_check BEFORE UPDATE ON account
FOR EACH ROW
BEGIN
IF NEW.amount < 0 THEN
SET NEW.amount = 0;
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END;//
delimiter ;
这个脚本在MySQL 终端(MySQL console)或Workbench工作正常。但当我通过JDBC接口执行这段SQL代码时报错了
com.mysql.jdbc.exceptions.jdbc4.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 //
原因是因为delimiter
关键字不是SQL标准的一部分,只在Mysql Console有效
所以只要删除delimiter
相关的语句就可以了
CREATE TRIGGER upd_check BEFORE UPDATE ON account
FOR EACH ROW
BEGIN
IF NEW.amount < 0 THEN
SET NEW.amount = 0;
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END;
allowMultiQueries
有的时候需要反复执行触发器创建命令,为了确保创建触发器成功,在执行CRETAE TRIGGER
语句之前,要先执行DROP TRIGGER
命令删除已有的同名触发器,如下:
DROP TRIGGER IF EXISTS upd_check ;
CREATE TRIGGER upd_check BEFORE UPDATE ON account
FOR EACH ROW
BEGIN
IF NEW.amount < 0 THEN
SET NEW.amount = 0;
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END;
通过JCBC接口执行又会报错:
com.mysql.jdbc.exceptions.jdbc4.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 'CREATE TRIGGER upd_check BEFORE UPDATE ON account
这是因为MySQL 的 JDBC 连接器有一个名为allowMultiQueries 的安全特性,默认为false
[关闭]. 关闭时,不允许一次执行多个SQL语句。
所以要在数据库的连接url中添加&allowMultiQueries=true
就可以解决此问题。
如果不希望修改数据连接URL,而且直接JDBC连接数据库,可以调用Connection java.sql.DriverManager.getConnection(String url, Properties info) throws SQLException
方法,将allowMultiQueries
通过Properties对象传递给JDBC连接方法,示例代码如下:
/**
* JDBC接口执行SQL脚本
* @param sql SQL代码
* @throws SQLException
*/
public void runSQL(String sql) throws SQLException{
Connection connection = null;
Statement stat = null;
try {
String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useInformationSchema=true";//&allowMultiQueries=true
// 加载并注册MySQL的JDBC驱动
Class<?> driverClass = Class.forName("com.mysql.jdbc.Driver");
DriverManager.registerDriver(Driver.class.cast(driverClass.newInstance()));
Properties info=new Properties();
// 设置连接用户名
info.put("user", "root");
// 设置允许执行多条SQL语句
info.put("allowMultiQueries","true");
connection = DriverManager.getConnection(url, info);
System.out.printf("sql string:n" sql "n");
stat = connection.createStatement();
stat.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null != stat)
{
stat.close();
}
if(null != connection){
connection.close();
}
}
}
参考资料
《23.3.1 Trigger Syntax and Examples》 《Error while creating trigger through JDBC on mysql5.5》 《6.3.5 Security》 《allowMultiQueries flag with JDBC and jOOQ》