mysql - 如何使用 .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
设置,它就可以工作。但即使是带有自定义分隔符的非常简单的触发器也会失败。
解决方案
在搜索其他人如何从 .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);
推荐阅读
- pandas - 如何匹配来自两个数据帧的相应数据?
- websocket - 将消息从 Kafka 路由到连接到应用程序服务器集群的 Web 套接字客户端
- python - 将 CSV 文件导入为 PySpark 数据集(不是数据框)
- visual-studio - 在 NuGet 中从 Entity Framework 6.2 升级到 6.3.0
- zsh - 使用带有 zparseopts 的关联数组
- javascript - 将变量操作数应用于运算符
- php - 如何在没有函数的 PHP 中设置和检索动态全局变量
- python - 我正在尝试从列表中删除死链接的 id(错误 403),但我的代码总是跳过一些 id,尽管它们已经死了,但它们重新出现在列表中
- google-app-engine - 云运行是否有套接字配额?
- sql - 如何重置 SQL Server 内置函数(DAY)