string sql = "Insert Into mytable" + $" (Id, Name, otherName) Values" +
$" ('{id}','{name}','{otherName}')";
using (SqlCommand cmd = new SqlCommand(sql, sqlConnection))
{
cmd.ExecuteNonQuery();
}
我的问题是:我的一些数据有类似的东西:在“otherName”列中,它们会有一些像“迈克的汽车”。 SQL服务器会将错误放在“'s”上,我不知道如何修复我的代码。
感谢您的阅读。抱歉我的英语不好。
答案 0 :(得分:2)
您需要使用参数,您将自己接受SQL注入攻击:
// These come from whatever your source which you have no control over.
int id = 12345;
string name = "Andrew";
string otherName = "Fred";
var sql = "Insert Into mytable (Id, Name, otherName) Values (@id, @name, @otherName)
using (var sqlQuery = new SqlCommand(sql, sqlConnection))
{
sqlQuery.Parameters.AddWithValue("@id", id);
sqlQuery.Parameters.AddWithValue("@name", name);
sqlQuery.Parameters.AddWithValue("@otherName", otherName);
sqlQuery.ExecuteNonQuery();
}