【问题标题】:MySqlCommand.Parameters.Add adds slashes to commandtext in c#MySqlCommand.Parameters.Add 在 c# 中的命令文本中添加斜杠
【发布时间】:2021-08-31 15:22:48
【问题描述】:

我正在尝试在 C# 控制台应用程序中执行参数化插入查询。 DB = MYSQL 8。

StringBuilder commandString = new StringBuilder("INSERT INTO testtable (testcol) VALUES ");
string testparam = "testvalue";
commandString.Append(string.Format("('{0}')", testparam));
commandString.Append(";");

string ConnString = "server = localhost; database = xxxxx; User = xxxxx; Password = xxxxx; port = 3306";

 MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = ConnString;
            conn.Open();

            Console.WriteLine(commandString);  //if I copy the commandstring from the console and into Mysql workbench it works.

using (MySqlCommand cmd = new MySqlCommand("@str", conn))
            {
                cmd.Parameters.Add("@str",MySqlDbType.Text).Value=commandString.ToString();
                cmd.ExecuteNonQuery();
            }

一切看起来都不错,commandString 没问题:INSERT INTO testtable (testcol) VALUES ('testvalue');

我收到一个异常,说明如下: MySql.Data.MySqlClient.MySqlException: '你的 SQL 语法有错误;查看与您的 MySQL 服务器版本相对应的手册,了解在第 1 行的“INSERT INTO testtable (testcol) VALUES (\'testvalue\');'' 附近使用的正确语法”

请注意“testvalue”周围消息中的转义斜线。我没有把它们放在那里,它们也没有出现在这一行之前的命令字符串中。这是导致错误吗?如果是这样,为什么?

如果我使用 cmd.Parameters.AddWithValue,我会得到相同的工作命令字符串,但会出现错误:System.FormatException:'输入字符串格式不正确。'但是,如果我将生成的命令字符串从调试器复制粘贴到 MySQL 工作台并执行它,它就可以工作。

【问题讨论】:

    标签: c# mysql


    【解决方案1】:

    您没有正确使用参数化查询,您不应该像这里那样将整个 SQL 字符串转换为参数:

    using (MySqlCommand cmd = new MySqlCommand("@str", conn))
    {
         cmd.Parameters.Add("@str",MySqlDbType.Text).Value=commandString.ToString();
         cmd.ExecuteNonQuery();
    }
    

    它不会直接进行文本替换,实际上你让事情变得比实际需要的更复杂一些。一个例子可能是:

    string ConnString = "server = localhost; database = xxxxx; User = xxxxx; Password = xxxxx; port = 3306";
    string testparam = "testvalue"; // realistically this might come from user input
    string sql = "INSERT INTO testtable (testcol) VALUES (@testcol)";
    
    using (var conn = new MySqlConnection(ConnString))
    using (var cmd = new MySqlCommand(sql, conn))
    {
        conn.Open();
        cmd.Parameters.Add("@testcol", MySqlDbType.Text).Value = testparam;
        cmd.ExecuteNonQuery();
    }
    

    【讨论】:

    • 感谢 GarethD 发布此示例!对于未来的读者:我确实在示例中添加了 conn.Open() 使其工作。
    • AddWithValue 可以安全地与 MySql 一起使用,顺便说一句
    猜你喜欢
    • 2021-08-24
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多