首页 > 解决方案 > 为什么我的 C# 代码没有更新 SQL Server 数据库,尽管我得到了正确的受影响行数

问题描述

我创建了以下代码:

public static bool setHeadword(int id, string headword)
{       
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\pms.mdf;Integrated Security=True";
    conn.Open();

    SqlCommand command = new SqlCommand("UPDATE headwords SET Headword = @headword WHERE Id = @id", conn);

    command.Parameters.AddWithValue("@headword", headword);
    command.Parameters.AddWithValue("@id", id);

    int result = command.ExecuteNonQuery();
    conn.Close();

    return true;
}

但是代码不起作用,因为数据库中的值没有改变。如果我在数据库中手动运行代码,则会发生更改。但它不适用于 C#。

结果变量也持有正确数量的受影响行(在这种情况下为 1)。

我不确定我是否必须刷新更改或其他内容。

感谢您的帮助和最诚挚的问候弗朗茨

标签: c#sql-server

解决方案


static void Update(int id, string headword)
{
   try
   {    
   //You should create connectionString with correct details otherwise fail connection
    string connectionString =
        "server=.;" +
        "initial catalog=employee;" +
        "user id=sa;" +
        "password=123";
    using (SqlConnection conn =
        new SqlConnection(connectionString))
    {
        conn.Open();
        using (SqlCommand cmd =
            new SqlCommand("UPDATE headwords SET Headword=@headword" +
                " WHERE Id=@Id", conn))
        {
            cmd.Parameters.AddWithValue("@Id", id);
            cmd.Parameters.AddWithValue("@headword", headword);

            int rows = cmd.ExecuteNonQuery();


        }
    }
   }
catch (SqlException ex)
{
    //Handle sql Exception
}

}


推荐阅读