![](/img/trans.png)
[英]Inserting Data in an Access Database from Visual Studio using C#
[英]Updating locally stored database from changes to multiple data grids ( Visual studio C#, Access database using OLEDB)
我正在嘗試,但是根據包含數據庫副本的數據網格發生的更改來更新本地存儲的數據庫,嚴重失敗。 我認為我遇到問題的原因是由於數據庫有兩個表,我將這些表放入了兩個數據網格中,但是只有一個數據集。 我對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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.