日期:2014-05-19  浏览次数:20618 次

请高手帮忙看一下!Query方法中的cmdParms的使用
protected   static   string   connectionString   =ConfigurationSettings.AppSettings[ "ConnectionString "];
///   <summary>
///   执行查询语句,返回DataSet
///   </summary>
///   <param   name= "SQLString "> 查询语句 </param>
///   <returns> DataSet </returns>
public   static   DataSet   Query(string   SQLString,params   SqlParameter[]   cmdParms)
{
using   (SqlConnection   connection   =   new   SqlConnection(connectionString))
{
//新建一个cmd
SqlCommand   cmd   =   new   SqlCommand();
PrepareCommand(cmd,   connection,   null,SQLString,   cmdParms);
using(   SqlDataAdapter   da   =   new   SqlDataAdapter(cmd)   )
{
DataSet   ds   =   new   DataSet();
try
{
da.Fill(ds, "ds ");
cmd.Parameters.Clear();
}
catch(System.Data.SqlClient.SqlException   ex)
{
throw   new   Exception(ex.Message);
}
return   ds;
}
}
}
///   <summary>
///   这是一个建产连接及执行语句
///   </summary>
///   <param   name= "cmd "> cmd </param>
///   <param   name= "conn "> 连接数据库 </param>
///   <param   name= "trans "> </param>
///   <param   name= "cmdText "> SQL </param>
///   <param   name= "cmdParms "> </param>
private   static   void   PrepareCommand(SqlCommand   cmd,SqlConnection   conn,SqlTransaction   trans,   string   cmdText,   SqlParameter[]   cmdParms)  
{
if   (conn.State   !=   ConnectionState.Open)
conn.Open();
cmd.Connection   =   conn;
cmd.CommandText   =   cmdText;
if   (trans   !=   null)
cmd.Transaction   =   trans;
cmd.CommandType   =   CommandType.Text;//cmdType;
if   (cmdParms   !=   null)  
{
foreach   (SqlParameter   parm   in   cmdParms)
cmd.Parameters.Add(parm);
}
}
我用了老是说没声明
我的代码是 System.Data.SqlClient.SqlParameter     prm1=new   SqlParameter( "@str ",SqlDbType.NVarChar,32);
prm1.Direction=ParameterDirection.Input;
this.DataGrid2.DataSource=db1.db.Query( "select   @prm1   from     book ",prm1);

------解决方案--------------------
System.Data.SqlClient.SqlParameter prm1=new SqlParameter( "@str ",SqlDbType.NVarChar,32);

@Str 这个你的确没申明