如何使用.NET MySql连接器在mariadb中使用DELIMITER?

时间:2018-09-21 06:36:39

标签: mysql asp.net .net mariadb

我正在使用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,它将起作用。但是,即使是带有自定义定界符的非常简单的触发器也会失败。

1 个答案:

答案 0 :(得分:0)

当从.NET搜索其他人如何在MySQL / MariaDB中成功使用定界符时,我发现了以下文章:https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-mysqlscript-delimiter.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);