C#数据库不从数据集更新。 SQLCommandBuilder

时间:2017-05-18 21:23:53

标签: c# sql-server

过去4小时一直困扰着我的问题。我的数据集得到了更改,但数据库没有。

作为“全球”变种而存在的东西:

    DatabaseConnection objConnect;        
    string conString;
    DataSet ds;
    int MaxRows;

我的表单加载初始化数据库连接:

            objConnect = new DatabaseConnection();
            conString = Properties.Settings.Default.memoDbConnectionString;
            objConnect.connection_string = conString;

我有这个按钮可以更改我的数据集并调用我的数据库更新。

    private void button5_Click(object sender, EventArgs e)
    {
        //

        objConnect.Sql = Properties.Settings.Default.userSQL;
        ds = objConnect.GetConnection;
        MaxRows = ds.Tables[0].Rows.Count;

        for (int i = 0; i < MaxRows; i++)
        {
            DataRow dRow = ds.Tables[0].Rows[i];
            if (nick == dRow.ItemArray[0].ToString())
                if (textBox4.Text == textBox5.Text)
                    if (textBox3.Text == dRow.ItemArray[1].ToString())
                    {
                        ds.Tables[0].Rows[i][1] = textBox5.Text;
                       //this is the interesting bit
                        DataSet changes = ds.GetChanges();

                            objConnect.UpdateDatabase(changes);

                        //-----
                        MessageBox.Show(nick);
                        MessageBox.Show(dRow[1].ToString());

                        break;
                    }
                    else MessageBox.Show("Old password is wrong.");
                else MessageBox.Show("Pass confirmation does not correspond.");
                    }
        }

我在DatabaseConnection类中使用的函数:

    public void UpdateDatabase(System.Data.DataSet ds)
    {
        System.Data.DataSet changes = ds.GetChanges();
        System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
        //stuff thats suppsed to help
        da_1.UpdateCommand = cb.GetUpdateCommand();
        //----
            da_1.Update(ds.Tables[0]);
        ds.AcceptChanges();
    }

da_1是一个sqlDataAdapter,它在函数外部声明,但是在函数之前将它归入函数中。

1 个答案:

答案 0 :(得分:0)

这个答案:

Ok, I'm going to take a guess here. Is the PacjenciDB.sdf included 
into Visual Studio project by any chance? Do you have the property" Copy 
to output folder" set to "Always" or something similar? It seems 
that every time you do a build you could be overwriting 
your output folder database file. Try putting the database in a folder 
that is not inside VS project.

 BTW, your code is OK.

来自this帖子帮助了我。 有一点需要注意的是,如果你从调试文件夹启动程序,它将没有问题,这有助于我找到问题。问题在于我将我的数据库作为数据源添加到项目中以及制作该连接字符串及其与eachother的相似性。从数据源中删除它并从解决方案资源管理器中的正确文件夹中重新添加它,为我修复了它。

相关问题