Reputation: 93
I am trying to update my database using SQL commands but it is not working.
id = primarykey
public void updateName(int id, string name)
{
using(var cmd = new SqlCommand("UPDATE person SET name = @name where id = @id", connect()))
{
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@name",name);
cmd.ExecuteNonQuery();
}
}
private SqlConnection connect()
{
string conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
var c = new SqlConnection(conStr);
c.Open();
return c;
}
What have I missed?
Upvotes: 2
Views: 3965
Reputation: 21776
Rewrite query as
UPDATE person SET name = @name where id = @id;
IF @@ROWCOUNT = 0
RAISERROR('No rows updated', 16,1)
check if there are exists some empty try ... catch{}
in call stack
person
tables in different schemasUpvotes: 2
Reputation: 10532
You should change the parameters addition order - with most providers it DOES matter.
So it should be not
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@name",name);
but rather
cmd.Parameters.AddWithValue("@name",name);
cmd.Parameters.AddWithValue("@id", id);
General rule: the order of calls to cmd.Parameters.AddWithValue
should be the same as the order of parameter occurence in the query.
Upvotes: 3