JDBC 4 MySQL在一个Statement中执行一条SQL语句的时候可以正确执行,如果同时执行多条,就会报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 ';....'),甚是费解。
经过网上查找,发现有两种解决办法:
1、最简单的办法,在MySQL的连接字符串中设置allowMultiQueries参数置为true,
如:jdbc.url=jdbc:mysql://localhost:3306/ibatis?useUnicode=true&characterEncoding=UTF-8& allowMultiQueries=true 即可。
2、在程序中对SQL语句以分号拆分成多条SQL语句,然后使用Statement的addBatch方法,最后executeBatch就行(此处推荐使用PreparedStatement addBatch() and executeBatch() and clearBatch())。
综上是因为mysql的JDBC驱动不支持这种写法,不过sqlserver的倒是支持,oracle的jdbc中甚至都不能出现分号 否则报java.sql.SQLException: ORA-00911: invalid character异常。
PS:MySQL设置了允许同时执行多条SQL语句后,将存在SQL注入的风险。参见:http://www.plhwin.com/2014/06/13/web-security-sql/