这取决于您使用的SQL数据库.例如,如果你想在MySQL中使用单引号文字,你需要使用反斜杠,Dangerous:'和一个转义的转义字符文字:\'.对于MS-SQL来说,事情是完全不同的,危险:' 逃脱:''.以这种方式转义数据时没有删除任何内容,它是一种表示控件字符(如文字形式的引号)的方法.
以下是从文档中获取MS-SQL和C#的参数化查询的示例:
private static void UpdateDemographics(Int32 customerID,
string demoXml, string connectionString)
{
// Update the demographics for a store, which is stored
// in an xml column.
string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
+ "WHERE CustomerID = @ID;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;
// Use AddWithValue to assign Demographics.
// SQL Server will implicitly convert strings into XML.
command.Parameters.AddWithValue("@demographics", demoXml);
try
{
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
Run Code Online (Sandbox Code Playgroud)
对于MySQL,我不知道您可以使用的参数化查询库.你应该使用mysql_real_escape_string()或者你可以使用这个函数:
public static string MySqlEscape(this string usString)
{
if (usString == null)
{
return null;
}
// SQL Encoding for MySQL Recommended here:
// http://au.php.net/manual/en/function.mysql-real-escape-string.php
// it escapes \r, \n, \x00, \x1a, baskslash, single quotes, and double quotes
return Regex.Replace(usString, @"[\r\n\x00\x1a\\'""]", @"\$0");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22706 次 |
| 最近记录: |