【发布时间】: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 工作台并执行它,它就可以工作。
【问题讨论】: