我如何使用 MyBatis 创建一个 alter table 语句?我的 SQLSyntaxErrorException:您的 SQL 语法有错误

How do I create an alter table statement with MyBatis? MySQLSyntaxErrorException: You have an error in your SQL syntax

我有以下

@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] c.s.s.m.StatMapper.updateFirstPartition : ==> Preparing: alter table stats reorganize partition ?,? into ( partition ? values less than (?) );
2019-09-30 21:58:23.093 DEBUG 13728 --- [ restartedMain] c.s.s.m.StatMapper.updateFirstPartition : ==> Parameters: p20180901(String), p20181001(String), p20181001(String), 2018-10-01(Date)

Caused by: org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. Cause: 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 ''p20180901','p20181001' into ( partition 'p20181001' values less than ('2018-10-' at line 1

如何使用 MyBatis 发出这个 alter table 语句?

语句应如下所示(p0p1 替换为 p20180901p20181001):

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

${} 是文本替换,#{}java.sql.PreparedStatement 中的占位符(有关详细信息,请参阅 FAQ)。 因此,使用您的代码,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}) "
  + ")")

我用 ${pFirst},${pSecond} 而不是 #{pFirst},#{pSecond} 解决了这个问题。