簡體   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