3

我必须将 SQL 语句作为字符串插入数据库,例如:

string content = "insert into myTable(content) values ('" + myContent + "')";
string sql = "insert into myTable2(sqlStatement) values ('" + content + "')";

显然这不起作用,因为'inside content,所以我添加了以下内容:

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

我确定变量content已更改,但仍有错误ExecuteNonQuery()

我也尝试了以下方法,都失败了:

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

1 回答 1

2

当你想在字符串中转义单引号时,不要使用\双引号而是双引号。例如,您要插入St. Peter's Chapel,它应该是

string content = "St. Peter''s Chapel"

作为旁注,这不是正确的方法。正确的方法是参数化值以避免从SQL Injection.

C# 代码片段:

string content = "St. Peter's Chapel"
string connStr = "connection string here";
string sqlStatement = "INSERT INTO tableName (content) VALUES (@content)";
using (SqlConnection conn = new SqlConnection(connStr))
{
    using(SqlCommand comm = new SqlCommand())
    {
        comm.Connection = conn;
        comm.CommandText = sqlStatement;
        comm.CommandType = CommandType.Text;

        comm.Parameters.AddWithValue("@content", content);

        try
        {
            conn.Open();
            comm.ExecuteNonQuery();
        }
        catch(SqlException e)
        {
            // do something with the exception
            // do not hide it
            // e.Message.ToString()
        }
    }
}

为了正确编码

  • using用于 propr 对象处理的use语句
  • 使用try-catch块来正确处理对象
于 2013-04-03T06:25:34.623 回答