首页 > 解决方案 > 如何使用 MyBatis 创建 alter table 语句?MySQLSyntaxErrorException:您的 SQL 语法有错误

问题描述

我有以下

@Mapper
public interface StatMapper {
    @Update("alter table stats reorganize partition #{pFirst},#{pSecond} into ( "
            + "partition #{pSecond} values less than (#{dSecond}) "
            + ");")
    public void updateFirstPartition(@Param("pFirst")String pFirst, @Param("pSecond")String pSecond, @Param("dSecond")LocalDate dSecond);

它给出了以下错误

2019-09-30 21:58:23.067 DEBUG 13728 --- [restartedMain] cssmStatMapper.updateFirstPartition : ==> 准备:alter table stats reorganize partition ?,? into ( 分区 ? 值小于 (?) );
2019-09-30 21:58:23.093 调试 13728 --- [restartedMain] cssmStatMapper.updateFirstPartition:==> 参数:p20180901(字符串)、p20181001(字符串)、p20181001(字符串)、2018 年 10 月 1 日(日期)

引起:org.springframework.jdbc.BadSqlGrammarException: ### 更新数据库时出错。原因:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 ''p20180901'、'p20181001' 附近使用的正确语法(分区 'p20181001' 值小于 ('2018-10-'

如何alter table使用 MyBatis 发布此声明?

该语句应如下所示(并由 andp0代替p1):p20180901p20181001

alter table stats reorganize partition p0,p1 into (
    partition p1 values less than ('2018-10-01')
);

标签: javaspringmybatisspring-mybatis

解决方案


${}是文本替换并且#{}是 a 中的占位符java.sql.PreparedStatement(有关详细信息,请参阅常见问题解答)。因此,使用您的代码,MyBatis 会生成一个准备好的语句,如下所示...

PreparedStatement ps = connection.prepareStatement(
  "alter table stats reorganize partition ?,? into (partition ? values less than (?))");

...它失败了,因为您不能使用占位符作为分区名称。

以下应该工作。

@Update("alter table stats reorganize partition ${pFirst},${pSecond} into ( "
  + "partition ${pSecond} values less than (#{dSecond}) "
  + ")")

推荐阅读