2011-05-24 25 views
1

我使用這個代碼片段在我的數據庫更新值:更新在ASP.NET

SqlConnection con = new SqlConnection(@"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=advCenter;Integrated Security=True"); 
string str = "[email protected]"; 
SqlCommand com2 = new SqlCommand("select [user_Account] from User in str where [user_Email][email protected]", con); 
SqlCommand com = new SqlCommand("update User set [user_Account]=? WHERE [[email protected]]", con); 
com.Parameters.AddWithValue("user_Account",str); 
com.Parameters.AddWithValue("@em",str); 
con.Open(); 
com.ExecuteNonQuery(); 
com2.ExecuteNonQuery(); 
con.Close(); 

,但我得到這個錯誤關鍵字「用戶」附近

不正確的語法。
第40行:com.ExecuteNonQuery();

回答

3

「用戶」是SQL中的保留字。裹在方括號表的名稱來指定它的東西名稱:你爲什麼要使用兩個單獨的SqlCommand對象

[User] 
0

?絕對不需要.....我會嘗試更新或選擇 - 不要將兩個完全獨立的操作混合到一個調用中......

另外:您應該使用參數化查詢來避免SQL注入攻擊,你應該把你的SqlConnectionSqlCommand對象放入使用塊中 - 試試這個:

string updateStmt = 
    "UPDATE dbo.[User] SET [user_Account] = @AccountValue WHERE [user_Email] = @UserEMail;"; 

using(SqlConnection con = new SqlConnection(@"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=advCenter;Integrated Security=True")) 
using(SqlCommand _cmd = new SqlCommand(updateStmt, con)) 
{ 
    _cmd.Parameters.Add("@AccountValue", SqlDbType.VarChar, 100).Value = str; 
    _cmd.Parameters.Add("@UserEMail", SqlDbType.VarChar, 100).Value = str; 

    con.Open(); 
    _cmd.ExecuteNonQuery(); 
    con.Close(); 
}