以下代码成功执行,cmd.ExecuteNonQuery的返回值返回1,表示该行已成功更新但数据库未真正更新。怎么会这样?我正在使用sqlserver2008。
public string updatePost(string id, string head, string body)
{
connection = new SqlConnection(connString);
string cmdStr = "update News set Header = '"+head+"' , [Text] = '"+body+"' where Id = "+int.Parse(id)+"";
string msg = String.Empty;
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(cmdStr, connection);
int effected = cmd.ExecuteNonQuery();
msg += "The 'News Post - id:"+id+"' was successfully updated. Rows effected:"+effected+"";
}
catch (Exception ex)
{
msg = "The attempt to update the 'News Post - id'" + id + " failed with message: " + ex.Message;
}
finally
{
connection.Close();
}
return msg;
}
答案 0 :(得分:1)
试试这个,这解决了一些问题(比如sql-injection),也许还有你的更新问题:
public string UpdatePost(string id, string head, string body)
{
string msg = "";
string cmdStr = "update News set Header = @header, [Text] = @body where Id = @id";
using (var con = new SqlConnection(connString))
{
try
{
con.Open();
using (var cmd = new SqlCommand(cmdStr, con))
{
cmd.Parameters.AddWithValue("@header", head);
cmd.Parameters.AddWithValue("@body", body);
cmd.Parameters.AddWithValue("@id", int.Parse(id));
int effected = cmd.ExecuteNonQuery();
msg += "The 'News Post - id:" + id + "' was successfully updated. Rows effected:" + effected + "";
}
} catch (Exception ex)
{
msg = "The attempt to update the 'News Post - id'" + id + " failed with message: " + ex.Message;
}
}
return msg;
}