2015-05-04 46 views
2

我在写登录脚本。但是当我想检查用户是否已经存在错误时:SQL Server错误“过程期望参数”

Additional information: Procedure or function 'checkIfUserExcist' expects parameter '@username', which was not supplied.

会显示出来。

当我使用一个参数执行存储过程时,它会成功。播种我的代码有问题,但我找不到错误。

这是存储过程:

@username varchar(50) 
as 
begin 
    SELECT count(*) 
    FROM lars.userAcces 
    WHERE username = @username 
end 

这是我的C#代码:

public static bool checkIfUserExists(string username) 
{ 
     int temp=0; 

     SqlConnection conn = SqlConn.openSqlConnection(); 
     conn.Open(); 

     SqlCommand com = new SqlCommand("checkIfUserExists", conn); 
     com.Parameters.AddWithValue("@username", username); 

     temp = Convert.ToInt32(com.ExecuteScalar().ToString()); 
     conn.Close(); 

     if (temp == 1) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
} 
+2

你真的应该在你的'SqlConnection'和'SqlCommand'周围使用'using'语句,这样如果一个异常被抛出的连接仍然被清除。你的'Convert.ToInt32(com.ExecuteScalar()。ToString());'有点冗余,你的查询已经返回一个int'(int)com.ExecuteScalar()'应该做同样的事情并且更快。 –

+0

不是你的代码的直接修复,但你真的应该读这个。 http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ –

回答

6

你需要告诉你的SqlCommand,它使用存储过程 - 就像这样:

SqlCommand com = new SqlCommand("checkIfUserExcist", conn); 
-- add this line here 
com.CommandType = CommandType.StoredProcedure; 
com.Parameters.AddWithValue("@username", username); 
+0

谢谢,帮助它工作! – tosorro

相关问题