2013-05-10 358 views
2

我从以下代码中遗漏了什么?在这段代码片段中,我从SQLite数据库的表中读取数据。然后,我正在更新一个单元格,然后读回这个更改。使用SqliteDataAdapter将更改写入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; 

回答

3

好的,明白了。我不得不重新定位/修改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; 
0
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); 
      } 
+1

你可能想阐述的解决方案,提供文本和原因的代码。 – 2016-12-29 20:14:18