【问题标题】:Can't save the dataset changes to the database in C# - Visual Studio 2013无法将数据集更改保存到 C# 中的数据库 - Visual Studio 2013
【发布时间】:2015-08-19 10:39:22
【问题描述】:

[已解决] 解决方案:当您在 Visual Studio 中执行程序时,它不会将更改提交到数据库,而是使用副本。当您将程序部署到可执行文件时,该可执行文件能够永久修改您的数据库。希望这对任何人都有帮助:)

正如我在这个问题HERE 中所说,我无法将数据集的更改保存到我的数据库中。我尝试按照本教程HERE 进行操作,但也无法正常工作:程序编译并执行,但新数据未提交给数据库。这是我在教程之后编写的代码。

//我的注册窗口表单中的方法

    public static SqlDataAdapter GetuserRecord()
    {
        SqlConnection connection = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\DatabaseJogo.mdf;Integrated Security=True");
        string query = "Select * from dbo.[user]";

        SqlCommand command = new SqlCommand(query, connection);
        connection.Open();
        SqlDataAdapter adp = new SqlDataAdapter(command);
        MessageBox.Show("CONNECTION SUCCESFUL");
        return adp;
    }

//当我的注册按钮被点击时:

            SqlDataAdapter adp = GetuserRecord();
            DataSet ds = new DataSet();

            adp.Fill(ds);

            DataRow newRow = ds.Tables[0].NewRow();
            newRow["login"] = loginText.Text.Trim();
            newRow["name"] = nameText.Text.Trim();
            newRow["age"] = int.Parse(ageText.Text.Trim());
            newRow["graphicsScore"] = trackBar1.Value;
            newRow["storyScore"] = trackBar2.Value;
            newRow["gameplayScore"] = trackBar3.Value;
            newRow["password"] = passwordText.Text.Trim();
            newRow["isAdmin"] = isAdmin.Checked;
            newRow["sex"] = sex.Text.Trim();

            ds.Tables[0].Rows.Add(newRow);

            SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adp);

            adp.UpdateCommand = commandBuilder.GetUpdateCommand(true);
            adp.InsertCommand = commandBuilder.GetInsertCommand(true);
            adp.DeleteCommand = commandBuilder.GetDeleteCommand(true);

            adp.Update(ds);

编辑:将代码更改为新代码,但问题仍然相同。如果你想看看,这里是:

                //TRY 3 SQL
            //https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqltransaction.commit(v=vs.110).aspx
            SqlConnection connection = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\DatabaseJogo.mdf;Integrated Security=True");
            connection.Open();

            SqlCommand command = connection.CreateCommand();
            SqlTransaction transaction;

            transaction = connection.BeginTransaction("SIGNUP");

            command.Connection = connection;
            command.Transaction = transaction;
            try
            {
                command.CommandText = "INSERT INTO [user] ([login], [name], [age], [graphicsScore], [storyScore], [gameplayScore], [password], [isAdmin], [sex]) VALUES (@login, @name, @age, @graphicsScore, @storyScore, @gameplayScore, @password, @isAdmin, @sex);";
                command.Parameters.Add("@login", SqlDbType.NChar, 50).Value = loginText.Text.Trim();
                command.Parameters.Add("@name", SqlDbType.NChar, 50).Value = nameText.Text.Trim();
                command.Parameters.Add("@age", SqlDbType.Int).Value = int.Parse(ageText.Text.Trim());
                command.Parameters.Add("@graphicsScore", SqlDbType.Int).Value = trackBar1.Value;
                command.Parameters.Add("@storyScore", SqlDbType.Int).Value = trackBar2.Value;
                command.Parameters.Add("@gameplayScore", SqlDbType.Int).Value = trackBar3.Value;
                command.Parameters.Add("@password", SqlDbType.NChar, 50).Value = passwordText.Text.Trim();
                command.Parameters.Add("@isAdmin", SqlDbType.Bit).Value = isAdmin.Checked;
                command.Parameters.Add("@sex", SqlDbType.NChar).Value = sex.Text.Trim();
                command.ExecuteNonQuery();

                transaction.Commit();
                MessageBox.Show("COMMITTED");
            }
            catch (Exception expt)
            {
                MessageBox.Show(expt.Message);
                try
                {
                    transaction.Rollback();
                }
                catch (Exception ex2)
                {
                    // This catch block will handle any errors that may have occurred 
                    // on the server that would cause the rollback to fail, such as 
                    // a closed connection.
                    MessageBox.Show("Rollback Exception Type: " + ex2.GetType());
                    MessageBox.Show("  Message: " + ex2.Message);
                }
            }
            //connection.UpdateDatabase(ds);

            connection.Close();

【问题讨论】:

  • 您是否提供了与数据库表列名相似的正确列名newRow["login"] - login- 这与表列名相似吗?列名可能区分大小写,因此请尝试给出确切的列名
  • 是的,我很高兴。使用此代码注册表格后,我可以登录我的帐户并查看我在注册屏幕中输入的所有详细信息。唯一的问题是,一旦我关闭程序,新用户就会从数据库中删除。
  • 你能在 try/catch 块中包装一下,看看你是否在那个更新上遇到了异常吗?
  • @ragerory 尝试使用 try { adp.Update(ds.Tables[0]); } catch(Exception expt) { MessageBox.Show(expt.Message); } 并且没有抛出异常!

标签: c# database visual-studio-2013 dataset


【解决方案1】:

为了更新数据库中的数据,您的 SqlDataAdapter 需要设置其 InsertCommand、UpdateCommand、DeleteCommand 属性。

所以,试试下面的代码:

 ds.Tables[0].Rows.Add(newRow);
 SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adp);
 adp.DeleteCommand = commandBuilder.GetDeleteCommand(true);
 adp.UpdateCommand = commandBuilder.GetUpdateCommand(true);
 adp.InsertCommand = commandBuilder.GetInsertCommand(true);
 adp.Update(ds.Tables[0]);
 //connection.UpdateDatabase(ds);
 connection.Close();

编辑: Update 方法采用 DataSet 和表的名称。我们的 DataSet 是 ds,它是我们在设置时传递给 UpdateDatabase 方法的那个。在一个点之后,键入数据集中表的名称。

【讨论】:

  • 没有解决整个问题。我做的第一种方法(使用内置表适配器)的工作方式与此例程的工作方式相同:数据保存到 DataSet 并且我可以访问我插入数据集中的新数据,但是当我关闭程序时新数据被清理。谢谢!
  • @RodrigoGuimarães :查看我的编辑...您必须在更新方法中传递数据集表,而我注意到的一件事是在执行插入/删除/更新操作后始终关闭连接。跨度>
  • 我试过了,关闭连接,改成adp.Update(ds.Tables[0]);,但问题依旧。再次感谢。
  • 命令connection.UpdateDatabase(ds);不可用,我在 Google 上一无所获。它属于什么命名空间?
  • @RodrigoGuimarães :抱歉,我的代码复制和粘贴错误。忽略它。
【解决方案2】:

我也会经历同样的事情:
我可以创建数据集,然后插入、更新和删除,然后显示更改后的数据集的数据。正如数据集的所有变化所显示的那样,这符合预期。但是你可以一次又一次地运行它,所以:底层数据库中的数据没有改变。

要么某处的某些最终提交丢失,要么它无法正常工作,并且这些方法不再是最新的,没有人关心。
真诚的 安迪

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    相关资源
    最近更新 更多