繁体   English   中英

如何在 JdbcTemplate 中创建 mySQL 存储过程

[英]How to create a mySQL stored procedure in a JdbcTemplate

背景

为了解决 MySql 中的问题,即某些语句只允许在存储过程中使用,我正在尝试创建、运行,然后在 JdbcTemplate 提交的 sql 中删除存储过程。 一个简单的例子是(这恰好在 spring boot 中):

@Service
public class StartupDatabaseCheck {
    private JdbcTemplate template;

    @Autowired
    public StartupDatabaseCheck(JdbcTemplate template){
        this.template = template;
    }

    @PostConstruct
    public void init() {
        log.info("Running custom fields table creation (if required)");
        try {
            String migrateSql = Resources.toString(Resources.getResource("migrateScript.sql"), Charsets.UTF_8);
            template.execute(migrateSql);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

migrateScript.sql 在哪里

DELIMITER //
CREATE PROCEDURE migrate()
BEGIN
    IF ((SELECT count(1)
         FROM INFORMATION_SCHEMA.COLUMNS
         WHERE table_name = 'custom_field_instance_data'
           and column_name='entity_id' and is_nullable = false) > 0)
    THEN
        alter table custom_field_instance_data MODIFY COLUMN entity_id char(32) null;
    END IF;
END //
DELIMITER ;

call migrate;

drop procedure migrate;

在 mySql 工作台中运行它工作正常,但由 JdbcTemplate 提交我收到错误

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 PROCEDURE migrate_custom_fields()

据我了解,这是因为JdbcTemplate 不允许这些DELIMITER语句而只是按照该链接中的建议删除它们会导致其他语法错误

如何通过 JdbcTemplate 创建 mySQL 存储过程(或通常只允许执行存储过程的语句)

笔记

没有分隔符语句的错误是

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 PROCEDURE migrate_custom_fields()

驱动程序似乎没有将分隔查询记入帐户。如果您想使用 jdbc 动态创建存储过程。 使用以下属性并将其作为 URL 中的连接参数传递。

jdbc:mysql://localhost:3306/test?allowMultiQueries=true

上述属性将允许';' 定界查询。 您可以在此处找到更多关于使用 JPA Hibernate 创建 MySQL 存储过程的信息

在这种情况下更新的 migrateScript.sql 将是

drop procedure IF EXISTS migrate_custom_fields;

CREATE PROCEDURE migrate_custom_fields()
BEGIN
    IF ((SELECT count(1)
         FROM INFORMATION_SCHEMA.COLUMNS
         WHERE table_name = 'custom_field_instance_data'
           and column_name='entity_id' and is_nullable = false) > 0)
    THEN
        alter table custom_field_instance_data MODIFY COLUMN entity_id char(32) null;
    END IF;
END ;

call migrate_custom_fields;

drop procedure migrate_custom_fields;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM