我必须将SQL语句作为字符串插入到数据库中,如:
string content = "insert into myTable(content) values ('" + myContent + "')";
string sql = "insert into myTable2(sqlStatement) values ('" + content + "')";
显然由于'
内的content
,这不起作用,所以我添加了以下内容:
Console.WriteLine(content);
content = content.Replace("'", "\\'");
Console.WriteLine(content);
我确定变量content
已更改,但ExecuteNonQuery()
我也试过以下,都失败了:
content = content.Replace("'", "\\\'");
content = content.Replace("'", "\\\\'");
content = content.Replace("'", @"\'");
答案 0 :(得分:2)
如果要在字符串中转义单引号,请不要使用\
,而应将引号加倍。例如,您要插入St. Peter's Chapel
,它应该是
string content = "St. Peter''s Chapel"
作为旁注,这不是正确的做法。正确的方法是参数化值以避免SQL Injection
。
C#Code Snippet:
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对象处理try-catch
块来正确处理对象