不错呦!smile@林凯西,确保“准备文件”中的几个文件都有安装,S...您好,看了您这篇帖子觉得很有帮助。但是有个问题想请...我的修改过了怎么还被恶意注册呢 @jjjjiiii 用PJ快9年了,主要是A...PJ3啊,貌似很少有人用PJ了,现在不是WP就是z...@332347365,我当时接入时错误码没有-10...楼主,ChkValue值应为-103是什么意思呢?...大哥 你最近能看到我发的信息,请跟我联系,我有个制...
多条件查询 VS 参数化查询
编辑:dnawo 日期:2009-09-18
一直以来对参数化查询有个误解:SqlCommand对象中,给Parameters添加参数的个数必须和CommandText中使用的变量个数相等。今天测试发现:
·CommandText中使用的变量在Parameters中必须有对应的参数;
·Parameters中参数的个数可以多于CommandText中使用的变量个数;
道理很简单,你在程序中使用的变量都必须先声明,但声明的变量没有要求说一定都得在程序中使用。
上边例子中,当categoryID=-1时,声明的@CategoryID变量就是多余的,但并不影响程序运行,这样在多条件查询下使用参数化查询写代码就简单多了。
·CommandText中使用的变量在Parameters中必须有对应的参数;
·Parameters中参数的个数可以多于CommandText中使用的变量个数;
道理很简单,你在程序中使用的变量都必须先声明,但声明的变量没有要求说一定都得在程序中使用。
复制内容到剪贴板
程序代码

/// <summary>
/// 产品搜索
/// </summary>
/// <param name="productName">产品名称</param>
/// <param name="categoryID">产品分类ID,-1时忽略</param>
/// <returns></returns>
private DataTable List(string productName, int categoryID)
{
DataTable table = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection("server=127.0.0.1;database=Northwind;user id=sa;password=sa"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
if (categoryID == -1)
cmd.CommandText = "select * from Products where ProductName=@ProductName";
else
cmd.CommandText = "select * from Products where ProductName=@ProductName and CategoryID=@CategoryID";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 100;
SqlParameter[] parms = new SqlParameter[]{
new SqlParameter("@ProductName", SqlDbType.NVarChar),
new SqlParameter("@CategoryID", SqlDbType.Int)
};
parms[0].Value = productName;
parms[1].Value = categoryID;
for (int i = 0; i < parms.Length; i++)
cmd.Parameters.Add(parms[i]);
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(table);
}
}
}
}
catch { }
return table;
}
/// 产品搜索
/// </summary>
/// <param name="productName">产品名称</param>
/// <param name="categoryID">产品分类ID,-1时忽略</param>
/// <returns></returns>
private DataTable List(string productName, int categoryID)
{
DataTable table = new DataTable();
try
{
using (SqlConnection conn = new SqlConnection("server=127.0.0.1;database=Northwind;user id=sa;password=sa"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
if (categoryID == -1)
cmd.CommandText = "select * from Products where ProductName=@ProductName";
else
cmd.CommandText = "select * from Products where ProductName=@ProductName and CategoryID=@CategoryID";
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 100;
SqlParameter[] parms = new SqlParameter[]{
new SqlParameter("@ProductName", SqlDbType.NVarChar),
new SqlParameter("@CategoryID", SqlDbType.Int)
};
parms[0].Value = productName;
parms[1].Value = categoryID;
for (int i = 0; i < parms.Length; i++)
cmd.Parameters.Add(parms[i]);
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(table);
}
}
}
}
catch { }
return table;
}
上边例子中,当categoryID=-1时,声明的@CategoryID变量就是多余的,但并不影响程序运行,这样在多条件查询下使用参数化查询写代码就简单多了。
评论: 0 | 引用: 0 | 查看次数: 5151
发表评论
请登录后再发表评论!