使用SqliteDataAdapter向SQLite数据库写入更改

本文关键字:数据库 SqliteDataAdapter SQLite 使用 | 更新日期: 2023-09-27 18:12:57

下面的代码缺少什么?在这个代码片段中,我正在从SQLite数据库中读取一个表。然后我正在更新一个单元格,然后读取更改。

这段代码是较长代码的简化版本,但它说明了问题所在。

代码完美地读取了表,但是AcceptChanges()没有回写任何内容。我通过重复读取并转到SQLiteAdmin并仔细阅读表来验证这一点。

我尝试添加"oLocalAdapter.Update(oLocalSet.Tables[0]);"行,但是这没有任何区别。我在搜索的时候看到的

using System.Data.SQLite;
// DATABASE (Local): Formulate the SQL command.
String strSqlCommand = "SELECT * FROM [tblTest] ORDER BY [IdPrimary] ASC;";
SQLiteCommand oLocalCommand = new SQLiteCommand(strSqlCommand, ClassEngine.Connection);
// DATABASE (Local): Get the data records.
SQLiteDataAdapter oLocalAdapter = new SQLiteDataAdapter(oLocalCommand);
DataSet oLocalSet = new DataSet();
oLocalAdapter.Fill(oLocalSet, "tblTest");
// Try to write to some changes.
String strValue = oLocalSet.Tables[0].Rows[0][8].ToString();
oLocalSet.Tables[0].Rows[0][8] = 9;
oLocalSet.Tables[0].AcceptChanges();
oLocalAdapter.Update(oLocalSet.Tables[0]);
// Clean up.
oLocalSet.Dispose();
oLocalAdapter.Dispose();
oLocalCommand.Dispose();
oLocalCommand = null;

使用SqliteDataAdapter向SQLite数据库写入更改

好的,知道了。

第一,我必须重新定位/修改AcceptChanges()行。

包括可能的

oLocalAdapter.AcceptChangesDuringUpdate = true;

然后我必须添加

SQLiteCommandBuilder oBuilder = new SQLiteCommandBuilder(oLocalAdapter);
oLocalAdapter.UpdateCommand = oBuilder.GetUpdateCommand();

最后一行是更新,它工作了。这使得代码:

// DATABASE (Local): Formulate the SQL command.
String strSqlCommand = "SELECT * FROM tblTest ORDER BY IdPrimary ASC;";
SQLiteCommand oLocalCommand = new SQLiteCommand(strSqlCommand, ClassEngine.Connection);
// DATABASE (Local): Get the data records.
SQLiteDataAdapter oLocalAdapter = new SQLiteDataAdapter(oLocalCommand);
DataSet oLocalSet = new DataSet();
oLocalAdapter.Fill(oLocalSet, "tblTest");
// 
SQLiteCommandBuilder oBuilder = new SQLiteCommandBuilder(oLocalAdapter);
// Try to write to some changes.
String strValue = oLocalSet.Tables[0].Rows[0][8].ToString();
oLocalSet.Tables[0].Rows[0][8] = 9;
strValue = oLocalSet.Tables[0].Rows[0][8].ToString();
oLocalSet.AcceptChanges();
oLocalAdapter.UpdateCommand = oBuilder.GetUpdateCommand();
oLocalAdapter.Update(oLocalSet.Tables[0]);
// Clean up.
oLocalSet.Dispose();
oLocalAdapter.Dispose();
oLocalCommand.Dispose();
oLocalCommand = null;
public void SaveDataTable(DataTable DT)
        {
        try
            {
            con.Open();
            cmd = con.CreateCommand();
            cmd.CommandText = string.Format("SELECT * FROM {0}", DT.TableName);
            adapter = new SQLiteDataAdapter(cmd);
            SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);
            adapter.Update(DT);
            con.Close();
            }
        catch (Exception Ex)
            {
            System.Windows.MessageBox.Show(Ex.Message);
            }