ToB企服应用市场:ToB评测及商务社交产业平台

标题: 办理bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorEx [打印本页]

作者: 络腮胡菲菲    时间: 2024-6-15 03:23
标题: 办理bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorEx
办理Spring Boot中MySQL数据库报错“Bad SQL Grammar”的问题


  
在使用Spring Boot连接MySQL数据库时,偶然候会遇到“Bad SQL Grammar”错误,这种错误通常在实行SQL语句时发生。本文针对的是对于实行多条SQL语句的情况。
问题描述

出现错误的SQL语句如下:
  1. <delete id="truncateUserInfo">
  2.     truncate table  sys_user;
  3.     truncate table  sys_user_info;
  4.     truncate table  sys_role_info;
  5. </delete>
复制代码
实行这个SQL语句时,可能会抛出BadSqlGrammarException,错误信息如下:
  1. org.springframework.jdbc.BadSqlGrammarException:
  2. ### Error updating database.  Cause: java.sql.SQLSyntaxErrorException: 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 'truncate table  sys_user_info;
  3.         truncate table  sys_role_info' at line 2
  4. ### The error may exist in file [...\CUserInfoMapper.xml]
  5. ### The error may involve defaultParameterMap
  6. ### The error occurred while setting parameters
  7. ### SQL: truncate table  sys_user;         truncate table  sys_user_info;         truncate table  sys_role_info;
  8. ### Cause: java.sql.SQLSyntaxErrorException: 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 'truncate table  sys_user_info;
  9.         truncate table  sys_role_info' at line 2
  10. ; bad SQL grammar []; nested exception is java.sql.SQLSyntaxErrorException: 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 'truncate table  sys_user_info;
  11.         truncate table  sys_role_info' at line 2
复制代码
同时,上层代码中调用该SQL语句的方法如下:
  1. this.baseMapper.truncateUserInfo();
复制代码
办理步调

起首确认SQL语句本身没有问题,并且该代码在其他项目中可以正常运行。确保底层SQL与上层调用的代码都没有逻辑问题,所以“bad SQL grammar []”应该是由设置文件导致的,查抄项目的application.yml文件中的MySQL连接设置参数
办理方案

这种错误通常是由于MySQL默认情况下不允许一次实行多个SQL语句,而这里的SQL语句包含了多个truncate语句。办理方案是在MySQL连接设置中添加allowMultiQueries=true参数,允许一次实行多个SQL语句。
找到项目的application.yml或application.properties文件,添加如下设置:
  1. datasource:
  2.     master:
  3.         url: jdbc:mysql://your-mysql-url:3306/your-database?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true&allowMultiQueries=true
  4.         # 其他配置项...
复制代码
这里的关键是在url参数中添加了&allowMultiQueries=true。这个设置项允许MyBatis实行多个SQL查询语句(以’;'分隔)。
结论

通过在MySQL连接设置中添加allowMultiQueries=true参数,我们乐成办理了实行多条SQL语句时出现的“Bad SQL Grammar”错误。这种设置的使用对于一些特殊的SQL语句实行场景非常有资助,但必要审慎使用,确保SQL语句的合法性和安全性。
附:MySql常用设置参数及使用场景

MySQL连接设置中有一些常用的参数,这些参数可以在数据库连接字符串(URL)中举行设置。以下是一些常见的MySQL连接参数及其使用场景和作用:
这些连接参数可以根据具体的需求举行设置,确保数据库连接的安全性和性能。在不同的场景中,可以机动选择和调整这些参数以满足应用程序的要求。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4