参数化查询(Parameterized Query )是指在设计与数据库链接并访问数据时,在需要填入数值或数据的地方,使用参数 (Parameter) 来给值,但是很多童鞋都不知道参数化查询有哪些好处。
1、防止SQL注入;2、提高查询性能(主要是可以复用查询计划),这点在数据量较大时尤为重要
一、防止SQL注入
参数化查询目前已被视为最有效可预防SQL注入攻击 (SQL Injection) 的攻击手法的防御方式,相信大家都知道这个,在这里我将不会多讲。
二、提高查询性能
一个简单的sql语句,通常有以下几种写法:
string sql=string.format(@"select userName from userInfo where Id={0}",id);
string sql=@"select userName from userInfo where Id="+id;
string sql=@"select userName from userInfo where Id=@id";
相信有一些基础的童鞋都知道字符串拼接的性能如何了,尤其是多次拼接。
这里只讲第三种,参数化查询,代码如下:

1 using System.Data; 2 using System.Data.SqlClient; 3 4 namespace HelperCommon 5 { 6 public class Error500 7 { 8 //通过用户id获取名字 9 public string GetUserNameById(int id) 10 { 11 string sql = @"select userName from userInfo where Id=@id"; 12 //参数为值类型(int,bigint,decimal,datetime等)指定参数类型即可,不必指定长度 13 SqlParameter para = new SqlParameter("@id",SqlDbType.Int); 14 para.Value = id; 15 16 object name= SqlHelper.ExecuteScalar(SqlHelper.Dev2, CommandType.Text, sql, para); 17 if (null == name) 18 return string.Empty; 19 return (string) name; 20 } 21 22 //通过用户名获取用户id 23 public int GetUserIdByName(string name) 24 { 25 string sql = @"select userName from userInfo where Id=@name"; 26 //参数类型为可变长度时(varchar,nvarchar,char等)请指定参数类型及长度 27 /*传值为varchar(max)或者nvarchar(max)时,参数长度指定为-1即可*/ 28 SqlParameter para = new SqlParameter("@name", SqlDbType.VarChar,5); 29 para.Value = name; 30 object id = SqlHelper.ExecuteScalar(SqlHelper.Dev2, CommandType.Text, sql, para); 31 if (null == name) 32 return 0; 33 return (int)id; 34 } 35 } 36 }
参数化查询可以提高查询性能(主要是可以复用查询计划),这点在数据量较大时尤为重要。