存储过程需要未提供的参数 - 原因是什么?

时间:2015-07-27 12:14:44

标签: sql-server ado

This is my error code

当我执行此异常时。

  

存储过程或函数需要未提供的参数。

这是我的代码:

string cs = ConfigurationManager.ConnectionStrings["conn"].ToString(); 

SqlConnection conn = new SqlConnection(cs); 
conn.Open(); 

SqlCommand cmd = new SqlCommand("sp_login",conn);  
cmd.Parameters.AddWithValue("@username",login.UserName.ToString()); 
cmd.Parameters.AddWithValue("@pass", login.Password); 

i = Convert.ToInt32(cmd.ExecuteScalar()); 

conn.Close();

1 个答案:

答案 0 :(得分:1)

您没有指定您正在调用存储过程 - 将代码更改为:

string cs = ConfigurationManager.ConnectionStrings["conn"].ToString(); 

// put connection and command into "using" blocks
using (SqlConnection conn = new SqlConnection(cs)) 
using (SqlCommand cmd = new SqlCommand("dbo.sp_login", conn))
{
    // tell your command that it's callign a *stored procedure*! 
    cmd.CommandType = CommandType.StoredProcedure;

    // don't use .AddWithValue - use .Add() and *SPECIFY* your datatype!
    cmd.Parameters.Add("@username", SqlDbType.VarChar, 50).Value = login.UserName.ToString()); 
    cmd.Parameters.Add("@pass", SqlDbType.VarChar, 50).Value = login.Password); 

    // open connection, execute query, close connection
    conn.Open(); 
    i = Convert.ToInt32(cmd.ExecuteScalar()); 
    conn.Close();
}