简体   繁体   English

如何在C#中创建MySql函数?

[英]How can I create a MySql function in C#?

I'm trying to create a mysql function in C#. 我正在尝试在C#中创建mysql函数。 The reason I'm doing this is because I want to loop through multiple mysql databases and create the function in each one. 我这样做的原因是因为我想遍历多个mysql数据库并在每个数据库中创建函数。

The problem is that the MySqlCommand does not like the DELIMITER syntax required to create the function. 问题在于MySqlCommand不喜欢创建函数所需的DELIMITER语法。 The script below executes fine in MySql clients, but does not work in this context: 下面的脚本在MySql客户端中可以很好地执行,但是在这种情况下不起作用:

DELIMITER //
DROP FUNCTION IF EXISTS cleandate //
CREATE FUNCTION cleandate(mydate DATE) 
RETURNS DATE
READS SQL DATA

BEGIN
RETURN  (CASE WHEN mydate <= '1900-01-01' THEN '1900-01-01' WHEN mydate = '0000-00-00' THEN '1900-01-01' 
        WHEN DATE_FORMAT(mydate, '%Y') = '0000' THEN '1900-01-01'
        WHEN DATE_FORMAT(mydate, '%m') = '00' THEN '1900-01-01'
        WHEN DATE_FORMAT(mydate, '%d') = '00' THEN '1900-01-01'
        ELSE mydate 
        END);
END//

The c# code trying to implement this(assuming connstrings is a List of strings): 尝试实现此功能的C#代码(假设connstrings是字符串列表):

foreach(var connstring in connstrings)
{
    // Create connection to database
    MySql.Data.MySqlClient.MySqlConnection dbConn = new MySql.Data.MySqlClient.MySqlConnection(connstring);

    MySqlCommand cmd = dbConn.CreateCommand();
    cmd.CommandText = @"[same script here]";

    try
    {
        dbConn.Open();
        cmd.ExecuteNonQuery();
    }
    catch (Exception erro)
    {
        Console.WriteLine(erro.ToString());                    
    }
}

I get the "syntax error near DELIMITER //" when I run this though. 我在运行此命令时收到“ DELIMITER //附近的语法错误”。 Any ideas how I can achieve this? 有什么想法可以实现这一目标吗?

The MySQL Connector offers a MySqlScript class that can be used in place of MySqlCommand when dealing with executing multiple statements and setting delimiters. MySQL连接器提供了一个MySqlScript类,可以在执行多个语句和设置定界符时代替MySqlCommand使用。

Adapted to your example: 适应您的示例:

foreach(var connstring in connstrings)
{
    MySqlConnection dbConn = new MySqlConnection(connstring);

    try
    {
        dbConn.Open();

        MySqlScript script = new MySqlScript(dbConn);

        script.Query = @"[same script here]";
        script.Delimiter = @"//";
        script.Execute();
    }
    catch (Exception error)
    {
        Console.WriteLine(error.ToString());                    
    }
}

https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-mysqlscript.html https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-mysqlscript.html

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

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