1

以下代码执行成功,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;
}

在此处输入图像描述

4

1 回答 1

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;
}
于 2013-07-24T22:32:36.493 回答