2015-05-04 47 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

相關問題