如何处理查询中的特殊字符..? [英] how to handle special character within the query..?
本文介绍了如何处理查询中的特殊字符..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,
我正在使用c#.net,我使用了一些查询来根据where子句从数据库中获取数据,现在问题了是我传递给where子句的值可能有也可能没有特殊字符(例如',',/或昏迷)。如何动态检查包含这些字符的值到数据库中的值。
例如:
string Description = Convert.ToString(dr [ Description]); // dr [Description]可能包含任何特殊字符
// 以下行是检查单引号
描述= Description.Replace( ', ''跨度>);
string ProductCode = Convert.ToString( SELECT [Code] FROM [Products] where Description =' + Description + '和[有效] ='1');
请帮帮我。
谢谢。
解决方案
使用SQL Command对象参数化您的查询。
使用(SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
使用 SqlCommand cmd = new SqlCommand(
产品中的SELECT代码WHERE描述= @description,con);
{
cmd.AddParameterWithValue( @ description,Description);
使用 SQL DataReader dr = cmd.ExecuteDataReader;
{
// 在此处插入您要对查询结果执行的操作
}
}
}
参数化防止SQL注入并处理特殊字符(在这种情况下,只是撇号)
Hello there,
I am working on c#.net and i have used few queries to get data from the database based on the where clause, Now the problem is the value i am passing to the where clause may or may not have special character (eg. ',",/ or coma). how can i dynamically check the value containing these characters to the value in database.
for Example :
string Description= Convert.ToString(dr["Description"]); // dr["Description"] may contain any special characters
//following line is to check the single quote
Description= Description.Replace("'","''");
string ProductCode= Convert.ToString("SELECT [Code] FROM [Products] where Description = '" + Description+ "' and [Active] = '1'");
please help me out.
thanks.
解决方案
Parameterize your query using a SQL Command object.
using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); using SqlCommand cmd= new SqlCommand( "SELECT Code From Products WHERE Description = @description", con); { cmd.AddParameterWithValue("@description", Description); using SQL DataReader dr = cmd.ExecuteDataReader; { // Insert what you want to do with query results here } } }
Parameterization protects from SQL injection AND deals with special characters (in this case, just the apostrophe)
这篇关于如何处理查询中的特殊字符..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文