Reputation: 11
I am using this code snippet to update values in my database :
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 [user_Email=@em]", con);
com.Parameters.AddWithValue("user_Account",str);
com.Parameters.AddWithValue("@em",str);
con.Open();
com.ExecuteNonQuery();
com2.ExecuteNonQuery();
con.Close();
but I get this error
Incorrect syntax near the keyword 'User'.
Line 40: com.ExecuteNonQuery();
Upvotes: 1
Views: 104
Reputation: 754268
Why are you using two separate SqlCommand
objects?? Absolutely not needed..... I would try to either UPDATE or SELECT - don't mix two totally separate operations into a single call....
Also: you should use parametrized queries to avoid SQL injection attacks, and you should put your SqlConnection
and SqlCommand
objects into using blocks - try this:
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();
}
Upvotes: 0
Reputation: 218808
"User" is a reserved word in SQL. Wrap the name of the table in square brackets to specify that it's the name of something:
[User]
Upvotes: 3