OledbDataAdapter 不更新表
本文关键字:更新 OledbDataAdapter | 更新日期: 2023-09-27 18:37:14
我在更新数据表时遇到问题。 我正在做的是这样的:
1)从数据库加载数据(我们称之为"旧数据库"
2)从其他数据库加载数据(我们称之为"新数据库")
3) 清除新数据库中的所有数据
4)将所有旧数据(来自旧数据库)合并到新数据库中
以下是我尝试实现此目的的方法:
string oldDatabase = this.txtOldReport.Text;
string newDatabase = this.txtNewReport.Text;
string backupFolder = @"C:'Planit'Report Updater'Backups";
if ( !Directory.Exists ( backupFolder ) ) {
Directory.CreateDirectory ( backupFolder );
}
string fullPath = Path.Combine ( backupFolder, string.Format ( @"Update Backup_{0}_{1}_{2}_{3}_{4}_{5}",
DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day,
DateTime.Now.Hour,
DateTime.Now.Minute,
DateTime.Now.Second) );
Directory.CreateDirectory ( fullPath );
File.Copy ( oldDatabase, Path.Combine ( fullPath, @"Old Report.mdb" ) );
File.Copy ( newDatabase, Path.Combine ( fullPath, @"New Report.mdb" ) );
OleDbConnection oldConnection = new OleDbConnection ( string.Format ( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", oldDatabase ) );
OleDbConnection newConnection = new OleDbConnection ( string.Format ( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", newDatabase ) );
OleDbCommand oldCommand = oldConnection.CreateCommand ( );
OleDbCommand newSelectCommand = newConnection.CreateCommand ( );
oldCommand.CommandText = @"SELECT * FROM Reports";
newSelectCommand.CommandText = @"SELECT * FROM Reports";
oldConnection.Open ( );
newConnection.Open ( );
DataSet oldDataset = new DataSet ( );
DataSet newDataset = new DataSet ( );
OleDbDataAdapter oldAdapter = new OleDbDataAdapter ( oldCommand );
OleDbDataAdapter newAdapter = new OleDbDataAdapter ( newSelectCommand );
OleDbCommandBuilder builder = new OleDbCommandBuilder ( newAdapter );
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
newAdapter.UpdateCommand = builder.GetUpdateCommand ( true );
newAdapter.InsertCommand = builder.GetInsertCommand ( true );
newAdapter.DeleteCommand = builder.GetDeleteCommand ( true );
oldAdapter.Fill ( oldDataset );
newAdapter.Fill ( newDataset );
newDataset.Tables [ 0 ].Rows.Clear ( );
// removed for a response below
//foreach ( DataRow dr in newDataset.Tables [ 0 ].Rows ) {
// dr.Delete ( );
//}
foreach ( DataRow dr in oldDataset.Tables [ 0 ].Rows ) {
dr.SetAdded ( );
newDataset.Tables [ 0 ].ImportRow ( dr );
}
// removed for the response below
//newDataset.AcceptChanges ( );
newAdapter.Update ( newDataset.Tables [ 0 ] );
oldConnection.Close ( );
newConnection.Close ( );
}
谁能看到我的问题? 当我调用"newAdapter.Update"时,没有任何反应。
感谢您的任何帮助。
MSDN 说
调用 AcceptChanges 时,任何 DataRow 对象仍处于编辑模式 成功结束其编辑。数据行状态也发生了变化:全部已添加 和修改的行变为"未更改",并且删除的行将被删除
所以,这条线
newDataset.AcceptChanges ( );
从导入的表中删除"添加的 RowState",当您调用 Update 时,数据库中没有要添加的行,因为newDataset
表中的每一行的状态都等于 Unchanged
因此,您只需要将其删除并再次调用您的newAdapter.Update
作为旁注,我认为您不需要遍历newDataset.Tables[0]来删除每一行,因为您之前已经调用了newDataset.Tables[0].Rows.Clear()