2012-06-15 46 views
0

當我通過給用戶名和密碼登錄,我得到一個異常:一個參數例外

「參數化查詢「(@username爲nvarchar(4000),@ password12 爲nvarchar(4000))SELECT我'期待 參數'@username',它沒有提供。「

通過代碼:

public DataSet showoption1(seter set) 
{   
    string sql = "SELECT menue.menuename,roleid, [right].rightname,   
    role.rolename, employee.employeename, employee.password FROM [right] INNER JOIN 
    permission ON [right].rightid = permission.rightid INNER JOIN role ON 
    permission.roleid = role.roleid INNER JOIN emp_men INNER JOIN employee ON 
    emp_men.employeeid = employee.employeeid ON role.roleid = employee.roleid 
    INNER JOIN menue ON emp_men.menueid = menue.menueid 
    where [email protected] 
    AND [email protected]"; 

    SqlCommand cmd = new SqlCommand(sql, con); 
    cmd.Parameters.AddWithValue("@username",set.Username); 
    cmd.Parameters.AddWithValue("@password12",set.Password); 
    SqlDataAdapter adptr = new SqlDataAdapter(cmd); 

    DataSet ds = new DataSet(); 
    adptr.Fill(ds); 
    int id= Convert.ToInt32(ds.Tables[2].Rows[0]["rooleid"]); 

    st.Username= Convert.ToString(ds.Tables[2].Rows[id]["roolename"]); 

    adptr.Dispose(); 

    return ds; 

    } 
+0

如果set.Username爲null,則不會創建該參數。你檢查了價值嗎? – stuartd

回答

2

由於DB的參數是如何工作的一個怪胎,如果set.Usernamenull會發生。因此:檢查set.Username是否爲null,並且可能在此情況下引發異常(因爲null用戶名聽起來像是一個錯誤)。

if(string.IsNullOrWhiteSpace(set.Username)) 
    throw new InvalidOperationException("No username was provided"); 

在更一般的情況,如果你想傳遞null,你必須使用DBNull.Value代替,即是這樣的:

object username = set.Username; 
if(username == null) username = DBNull.Value; 
cmd.Parameters.AddWithValue("@username", username); 
+0

我查了用戶名爲空,但我提供用戶名 – user1405508

0

你有兩個內部連接回不背相應的ON ...是導致解析錯誤?

SELECT 
     menue.menuename, 
     roleid, 
     [right].rightname, 
     role.rolename, 
     employee.employeename, 
     employee.password 
    FROM 
     [right] 
     INNER JOIN permission 
      ON [right].rightid = permission.rightid 
      INNER JOIN role 
       ON permission.roleid = role.roleid 
       INNER JOIN employee 
        ON role.roleid = employee.roleid 
        INNER JOIN emp_men 
        ON emp_men.employeeid = employee.employeeid 
        INNER JOIN menue 
         ON emp_men.menueid = menue.menueid 
    where 
      employee.employeenamee = @username 
     AND [email protected]"; 
0

我認爲最可能的解釋是,set.Username爲空。

使用調試器逐個檢查並檢查值。