谷歌搜索出各种讨论关于对Web访问进行查询的清理,但我没有找到任何解决我所关注的问题的内容:
在c#程序中清理用户输入数据。这必须通过可逆变换而不是删除来完成。举个简单的例子,我不想破坏爱尔兰人的名字。
最佳方法是什么,并且是否有任何库函数可以执行此操作?
谷歌搜索出各种讨论关于对Web访问进行查询的清理,但我没有找到任何解决我所关注的问题的内容:
在c#程序中清理用户输入数据。这必须通过可逆变换而不是删除来完成。举个简单的例子,我不想破坏爱尔兰人的名字。
最佳方法是什么,并且是否有任何库函数可以执行此操作?
这要看你使用的SQL数据库是什么。例如,在MySQL中,如果想要单引号文字,需要使用反斜杠,不安全的写法是:'
,转义后的字符文字是:\'
。在MS-SQL中,情况完全不同,不安全的写法是:'
,转义后是:''
。这种方式并不会删除任何数据,而是一种表示控制字符(例如引号)在其字面形式下的方法。
以下是从文档中提取的使用C#和MS-SQL参数化查询的示例:
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);
}
}
}
对于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");
}
public class SomeDal
{
public void CreateUser(User userToBeCreated)
{
using(connection bla bla)
{
// create and execute a command object filling its parameters with data from the User object
}
}
}
public class User
{
public string Name { get; set; }
...
}
public class UserBL
{
public CreateUser(User userToBeCreated)
{
SomeDal myDal = new SomeDal();
myDal.CreateUser(userToBeCreated);
}
}
public class SomeUI
{
public void HandleCreateClick(object sender, e ButtonClickEventArgs)
{
User userToBeCreated = new User() { Name = txtName.Text };
UserBL userBl = new UserBL();
userBl.CreateUser(userToBeCreated);
}
}