sql - 创建 MySQL 字符串 "safe"(转义双引号)

标签 sql escaping double-quotes

我需要通过 C# 将文本插入到 MySQL 表中。 dbConnect 是我自己创建的适配器,ProcessNonQuery 仅接受一个字符串。

我无法插入包含字符 "' 的文本。

这是我的尝试:

public void InsertArticle(string name, string title, string keywords, string desc, string content, int idCategory,bool featured)// int level, int typeArt
{                        
    this.dbConnect.ProcessNonQuery(" set global sql_mode=\"NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\"");
    string strFeatured;

    if (featured)
        strFeatured = "1";
    else
        strFeatured = "0";
    content = content.Replace("'", "\'");
    StringBuilder sbInsertArticle = new StringBuilder("INSERT INTO Article(NameArt, TitleArt, keywordsArt, DescArt, ContentArt, idCategory, idLevel, idTypeArt, Featured) VALUES('");
    sbInsertArticle.Append(name); sbInsertArticle.Append("', '");
    sbInsertArticle.Append(title); sbInsertArticle.Append("', '");
    sbInsertArticle.Append(keywords); sbInsertArticle.Append("', '");
    sbInsertArticle.Append(desc); sbInsertArticle.Append("', '");
    sbInsertArticle.Append(content); sbInsertArticle.Append("', '");
    sbInsertArticle.Append(idCategory.ToString()); sbInsertArticle.Append("', '");
    sbInsertArticle.Append(1); sbInsertArticle.Append("', '");
    sbInsertArticle.Append(1); sbInsertArticle.Append("', '");
    sbInsertArticle.Append(strFeatured); sbInsertArticle.Append("')");

    string strInsertArticle = sbInsertArticle.ToString();
    this.dbConnect.ProcessNonQuery(strInsertArticle);

}

最佳答案

连接器可能没有任何问题。发布的代码的输出不会正确转义内容。

如果 content = 它不起作用 那么输出类似于:

INSERT INTO Article(NameArt, TitleArt, keywordsArt,
  DescArt, ContentArt, idCategory, idLevel, idTypeArt, Featured)
  VALUES('foo', 'bar', 'mysql escaping', 'hmph',
    'it's don"t working', '12', '1', '1', '1');

这在任何连接器中都应该失败。

content = content.Replace("'", "\\'");

将是一个开始,但您至少应该使用类似mysql_real_escape_string()的东西。

编辑:进一步解释

在测试程序中运行以下几行:

Console.WriteLine("'");
Console.WriteLine("\'");
Console.WriteLine("\\'");

前两个将输出'。最后将输出\'

最后,由于您选择向调用者提供的接口(interface),这个问题无法在 MySQL 中解决,也无法在您的连接器中解决。 void ProcessNonQuery(string strParam) 过于简单,无法进行参数化查询,而参数化查询是将“转义”工作插入 API 所必需的。

因此,使用此“连接器”获得的任何解决方案都将特定于您调用它的语言 (C#),因为在进入 DB 或 API 层之前必须解决转义问题。许多人认为这种方法很糟糕,这就是为什么他们敦促您直接使用任何标准 MySQL 连接器,而不是尝试将其中一个包装到您自己的 API 中。

关于sql - 创建 MySQL 字符串 "safe"(转义双引号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13977744/

相关文章:

PostgreSQL:如何避免 COPY 命令输出中不需要的字符?

php - 使用 MySQL 示例员工数据库的 SQL 查询

sql - 如何连接到 LabView 中的数据库

javascript - 在数据属性 JSON 对象中转义引号和 html

windows - 何时以及在批处理文件中的 FOR/F 和 WMIC 中转义什么

python - 如何在 CSV 字段中将双引号内的双引号替换为空字符?

Grails - 在参数中转义双引号

swift - 在 Swift 中测试字符串中的双引号字符

sql - 如何按两列分组以仅显示一行?

mysql - SQL:查找表中的所有行,其中引用原始行的另一个表中的所有行都具有特定属性