首页 > 解决方案 > 如何使用 .NET MySql 连接器在 mariadb 中使用 DELIMITER?

问题描述

我正在使用 MariaDB 10.2.12 并使用 .NET MySQL 连接器进行连接。以下触发器在 MySQL Workbench 中工作正常:

DELIMITER //
CREATE TRIGGER update_last_modified
BEFORE UPDATE ON users
FOR EACH ROW
BEGIN
    DECLARE miscdataWithDate JSON;
    IF JSON_CONTAINS_PATH(NEW.miscdata, 'all', '$.v1.lastModified2') THEN
        SET NEW.miscdata = JSON_REPLACE(NEW.miscdata, '$.v1.lastModified2', UTC_TIMESTAMP());
    ELSE
        SET miscdataWithDate = JSON_SET('{"v1": {}}', '$.v1.lastModified2', UTC_TIMESTAMP());
        SET NEW.miscdata = JSON_MERGE(NEW.miscdata, miscdataWithDate);
    END IF;
END; //
DELIMITER ;

要从 C#/.NET 运行命令,我使用了以下命令。我尝试使用和不使用最后的分号,以防图书馆添加分号:

using (var cmd = new MySqlCommand(@"CREATE TRIGGER update_last_modified
    BEFORE INSERT ON users
    FOR EACH ROW
    BEGIN
        DECLARE miscdataWithDate JSON;
        IF JSON_CONTAINS_PATH(NEW.miscdata, 'all', '$.v1.lastModified') THEN
            SET NEW.miscdata = JSON_REPLACE(NEW.miscdata, '$.v1.lastModified', UTC_TIMESTAMP());
        ELSE
            SET miscdataWithDate = JSON_SET('{""v1"": {}}', '$.v1.lastModified', UTC_TIMESTAMP());
            SET NEW.miscdata = JSON_MERGE(NEW.miscdata, miscdataWithDate);
        END IF;
    END; //
    DELIMITER ;", connection))
{
    await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
}

当触发器被定义(未调用)时,错误是:

Unhandled Exception: System.AggregateException: One or more errors occurred. (You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '//
    DELIMITER' at line 1) ---> MySql.Data.MySqlClient.MySqlException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '//
    DELIMITER' at line 1

如果我简化查询使其不需要DELIMITER设置,它就可以工作。但即使是带有自定义分隔符的非常简单的触发器也会失败。

标签: mysqlasp.net.netmariadb

解决方案


在搜索其他人如何从 .NET 成功使用 MySQL/MariaDB 分隔符时,我发现了以下文章:https ://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-mysqlscript-分隔符.html

给出的示例使用MySqlScript而不是MySqlCommand,因此我相信它MySqlCommand根本不支持分隔符。这是更新的代码,可以正常工作:

MySqlScript script = new MySqlScript(connection, @"CREATE TRIGGER update_last_modified
    BEFORE INSERT ON users
    FOR EACH ROW
    BEGIN
        DECLARE miscdataWithDate JSON;
        IF JSON_CONTAINS_PATH(NEW.miscdata, 'all', '$.v1.lastModified') THEN
            SET NEW.miscdata = JSON_REPLACE(NEW.miscdata, '$.v1.lastModified', UTC_TIMESTAMP());
        ELSE
            SET miscdataWithDate = JSON_SET('{""v1"": {}}', '$.v1.lastModified', UTC_TIMESTAMP());
            SET NEW.miscdata = JSON_MERGE(NEW.miscdata, miscdataWithDate);
        END IF;
    END; //");
script.Delimiter = "//";
await script.ExecuteAsync().ConfigureAwait(false);

推荐阅读