3

次のように、SQL ステートメントを文字列としてデータベースに挿入する必要があります。

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

明らかに、これは'insidecontentのために機能しないため、次を追加しました。

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適切なオブジェクトの破棄には useステートメント
  • ブロックを使用try-catchしてオブジェクトを適切に処理する
于 2013-04-03T06:25:34.623 に答える