读书人

此 SqlParameterCollection 中未包含带

发布时间: 2012-02-04 15:43:09 作者: rapoo

此 SqlParameterCollection 中未包含带有 ParameterName“RETURNVALUE”的 SqlParameter
问题是这样的:
通过sqlact类,执行一个sql语句
new SQLAct().RunSql("update users set u_geziid="+gid+",u_shopid="+Shopid+" where u_name=(select g_username from gezi where g_id="+gid+")");

类中的方法如下。
public int RunSql(string strSql)
{
Open();
///创建Command
SqlCommand thisCommand = new SqlCommand(strSql, Conn);
thisCommand.CommandType = CommandType.Text;
thisCommand.ExecuteNonQuery();
return (int)thisCommand.Parameters[RETURNVALUE].Value; ---结果是错在这里“此 SqlParameterCollection 中未包含带有 ParameterName“RETURNVALUE”的 SqlParameter” }

不明白原因,请大家指教

[解决办法]
你执行的 SQL语句确实没有 返回参数

返回 参数 基本上 是过程中才有的
声明时 带个 out 关键字

你不就想 确定 是否 执行 了
可以这样

C# code
//num 影响行数 int num = thisCommand.ExecuteNonQuery();
[解决办法]
给你改改你的方法
C# code
 
public Boolean RunSql(string strSql) {

SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["conStr"]);
conn.Open();
SqlCommand cmd = new SqlCommand(sQueryString, conn);
try
{

cmd.ExecuteNonQuery();
conn.Close();
}
catch (System.Exception e) {

conn.Close();
return false;
}
return true;
}

[解决办法]
建议看一下参数化查询
你的写法还是拼接SQL语句的方式,.net中提供了参数化方式,可以防止SQL注入而且是SQL语句写起来更简单。
return (int)thisCommand.Parameters[RETURNVALUE].Value;
你的这句代码会从参数集合中找到存储过程的返回值,没有返回值所有报错。给你段示例代码看下:
C# code
public static void Sql_Operation(string userID)    {         using (SqlConnection myConncetion = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]))        using (SqlCommand myCommand = new SqlCommand("select UserID, UserName, UserPwd from WHERE userID = @userID ", myConncetion))        {            try            {                //构造参数                SqlParameter myParameter = new SqlParameter("@userID",SqlDbType.Int,4);                //为参数赋值                myParameter.Value = Int32.Parse(userID);                //将参数加入command对象的参数集合中                myCommand.Parameters.Add(myParameter);                myConncetion.Open();                myCommand.ExecuteNonQuery();            }            catch (Exception err)            {                throw new Exception("Err info:"+err.Message.ToString())            }            finally            {                myDataAdapter.Dispose();                myConncetion.Close();                myConncetion.Dispose();            }        }    } 

读书人网 >asp.net

热点推荐