2012-06-26 112 views
0

我必須將字符串數組中的值與數據庫中特定列的值進行比較。我該怎麼做呢 ?將字符串的值與數據庫值進行比較

public void setvisibility(string user_ID) 
{ 
    SqlDataReader reader = null; 
    SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ctd_prrity_dbConnectionSting"].ConnectionString); 
    connection.Open();\ 
SqlCommand cmd = new SqlCommand("Select * from Admins); 

我需要將user_ID的值與Admins表中的唯一列進行比較!

回答

0

這裏是你如何能做到這一點:

using(SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ctd_prrity_dbConnectionSting"].ConnectionString)) 
{ 
    connection.Open(); 
    SqlCommand cmd = new SqlCommand("Select 1 from Admins where [email protected]",connection); 
    cmd.Parameters.AddWithValue("@userid",user_ID); 
    SqlDataReader reader= cmd.ExecuteReader(); 
    if(reader.HasRows) 
    { 
    //user id found 
    } 
} 

此方法使用參數化查詢,這是從1995年起他在託尼的回答給出的選項更安全很容易出現SQL Injection攻擊。

順便說一句:你在你的問題中提到「字符串數組」,但你的代碼只顯示一個字符串作爲參數。你是什​​麼意思?

+0

我得到用戶ID字符串userID = User.Identity.Name.Split('\\')[1];像這樣,所以它基本上是一個字符串抱歉的混淆 – Pradit

+0

糾正我,如果我錯了,你是否獲得用戶名登錄在機器上?因此,例如你的Windows用戶名設置類似於「域\\用戶ID」,你只是分裂在'\\'採取用戶ID? – Tony318

+0

是的,這是完全正確的。 這就是我得到的 錯誤'System.Data.IDataReader'沒有包含'HasRows'的定義,也沒有找到接受'System.Data.IDataReader'類型的第一個參數的擴展方法'HasRows' – Pradit

0
sqlcommand("SELECT * FROM Admins WHERE column = " & user_ID); 

這應該有效。如果它與user_ID相同,它會返回列中的值。基本上,如果你的查詢返回一個值你有一個匹配,如果沒有,那麼你不會。

+0

並記住在傳遞到數據庫之前清理所有變量 –

相關問題