从对多个数据网格的更改更新本地存储的数据库(Visual Studio C#,使用 OLEDB 的 Access 数据库



我正在尝试根据包含数据库副本的数据网格发生的更改更新本地存储的数据库,但失败了。我认为我遇到问题的原因是由于数据库有两个表,我已经将它们放入两个数据网格中,但所有数据集都是一个数据集。我对OLEDB的了解有限,但是我已经创建了多个程序,其中包含如下所示的更新例程,因此我不确定如何适应这个新程序。

工作程序中表格的屏幕截图

变量

OleDbConnection Connection;
OleDbDataAdapter oledbAdapter;
OleDbCommandBuilder oledbCmdBuilder;
//DataSet ds = new DataSet();
string ConnectionString = null;
int CurrentRow = 0;
DataSet ds = new DataSet();

数据库连接 - 在加载时执行

private void database_datagrid_load()
{
string SQL1 = "SELECT * FROM tbl_Customers";       
string SQL2 = "SELECT * FROM tbl_Jobs";                     
Connection = new OleDbConnection(ConnectionString);         
try                                                         
{
ds.Clear();
Connection.Open();
oledbAdapter = new OleDbDataAdapter(SQL1, Connection);
oledbAdapter.Fill(ds, "tbl_Customers");
oledbAdapter.SelectCommand.CommandText = SQL2;
oledbAdapter.Fill(ds, "tbl_Jobs");
oledbAdapter.Dispose();
Connection.Close();
database_datagrid_customer.DataSource = ds.Tables[0];
database_datagrid_jobs.DataSource = ds.Tables[1];

}
catch(Exception ex)
{
MessageBox.Show(Convert.ToString(ex));
}
}

只有没有崩溃的更新代码 - 它已完成,但不对数据库进行任何更改

Connection.Open();
string SQL = "SELECT * FROM tbl_Jobs"; 
OleDbDataAdapter oledbAdapterNEW = new OleDbDataAdapter(SQL, Connection); //new adapter with just jobs table ignoring customers for now

OleDbCommandBuilder oledbCmdBuilderNEW = new OleDbCommandBuilder(oledbAdapterNEW); //cmdbuilder is set but never used not sure why  
DataSet changes = ds.GetChanges();


if (changes != null)
{
oledbAdapterNEW.Update(ds.Tables[0]);
}
ds.AcceptChanges();
MessageBox.Show("Jobs Save Changes");

不是正面的,但我认为应该是

if (changes != null)
{
ds.Tables[0].AcceptChanges();
//oledbAdapterNEW.Update(ds.Tables[0]);
}

想通了,这是那些需要它的人的解决方案。更新两个表。

private void database_btn_updatedb_Click(object sender, EventArgs e)
{
Connection = new OleDbConnection(ConnectionString);
DataSet changes = ds.GetChanges();
try
{
Connection.Open();
string SQL = "SELECT * FROM tbl_Jobs"; 
OleDbDataAdapter oledbAdapterNEW = new OleDbDataAdapter(SQL, Connection); //new adapter with just jobs table ignoring customers for now
OleDbCommandBuilder oledbCmdBuilderNEW = new OleDbCommandBuilder(oledbAdapterNEW); 

if (changes != null)
{
oledbAdapterNEW.Update(ds,"tbl_Jobs");
MessageBox.Show("Jobs Save Changes");
}
SQL = "SELECT * FROM tbl_Customers";
oledbAdapterNEW = new OleDbDataAdapter(SQL, Connection);
oledbCmdBuilderNEW = new OleDbCommandBuilder(oledbAdapterNEW);
if (changes != null)
{
oledbAdapterNEW.Update(ds, "tbl_Customers");
MessageBox.Show("Customer Save Changes");
}
ds.AcceptChanges();
Connection.Close();
}

最新更新