使用 C# 插入 MySQL 数据库表,可以包含双引号的字符串

本文关键字:包含双 字符串 插入 MySQL 数据库 使用 | 更新日期: 2023-09-27 17:56:21

我想使用C#插入MySQL数据库表中,一个可以包含双引号的字符串。这是我到目前为止尝试过的(首先转义双引号,然后将字符串括在双引号之间):

string sqlStr = "INSERT INTO table(ID, Comment) VALUES ";
foreach (KeyValuePair<string, string> kvp in myDict)
{
    string id = kvp.Key;
    string comment = String.Format("'"{0}'"", kvp.Value.Replace(@"""", @"'"""));
    sqlStr +=  String.Format("({0}, {1}), ";
}
// strip last comma
sqlStr = sqlStr.Substring(0, sqlStr.Length - 2);
conn.DoSql(sqlStr);

但这仍然给出了我的SQL语法不正确的错误。正确的方法是什么?

使用 C# 插入 MySQL 数据库表,可以包含双引号的字符串

SQL 使用单引号将字符串括起来。 这意味着字符串中的双引号不需要转义,但单引号需要转义。 假设字符串中没有任何单引号或撇号,则代码应为:

string sqlStr = "INSERT INTO table(ID, Comment) VALUES ";
foreach (KeyValuePair<string, string> kvp in myDict)
{
    string id = kvp.Key;
    string comment = String.Format("'{0}'", kvp.Value);
    sqlStr +=  String.Format("({0}, {1}), ";
}
// strip last comma
sqlStr = sqlStr.Substring(0, sqlStr.Length - 2);
conn.DoSql(sqlStr);

在执行 SQL 语句之前尝试打印它并检查它的内容

// firt do this
Console.WriteLine(sqlStr);
// and then this
conn.DoSql(sqlStr);

发布sqlStr的内容,如果你能:)