我有一些我用C#编写的代码来更新表格。虽然代码运行时没有引发错误,但表格没有更新。
如果我使用SQL命令并在SSMS查询窗口中运行它确实有效。
以下是代码:
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是表的主键,因此只更新特定行。
答案 0 :(得分:2)
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);
....