我有一些我用C#编写的代码来更新表。虽然代码运行时不会产生错误,但表格不会更新。C#SQL更新语句不更新
如果我使用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是表所以只有特定行被更新的主键。
您的查询看起来像在执行之前的样子吗?什么是你的专栏类型?顺便说一句,你应该总是使用[参数化查询](http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/)。这种字符串连接对于[SQL注入](http://en.wikipedia.org/wiki/SQL_injection)攻击是开放的。 –
'ExecuteNonQuery'方法返回一个数字,表示它所影响的行数。你检查了结果变量吗,它是0吗?如果是这样,那么你的'where'子句只是不匹配任何行。具体来说,'ID'是什么?内容是什么?你正在执行的最终SQL是什么? –
在你做任何事情之前,你需要阅读,理解并开始使用参数化查询。此代码易受sql注入攻击。 –