Reputation: 155
I have some code I've written in C# that is to update a table. While the code runs without raising an error, the table doesn't get updated.
If I take the SQL command and run in the SSMS query window it does work.
Here's the code:
try
{
string connectionString = "Server=XXXX;Database=XXX;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "update address set central_phone_number = '" + NewPhoneNumber + "'" + " where id = " + ID;
connection.Open();
int result = command.ExecuteNonQuery();
connection.Close();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "SQL Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
id is the primary key for the table so only a specific row gets updated.
Upvotes: 0
Views: 1683
Reputation: 14389
obviously, since you concatenate id with your query string, id is a string in your program. However id datatype in your DB is an int. You will solve your issue (as well as other issues like injection) simple by using parameters:
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "update address set central_phone_number =@num where id = @ID";
command.Parameters.AddWithValue("@num", NewPhoneNumber);
command.Parameters.AddWithValue("@ID",ID);
....
Upvotes: 2