2011-03-30 56 views
1

我嘗試使用TableDirect類型的SqlCeCommand將數百條記錄插入到空數據庫表中。問題是我調用SqlCeResultSet :: Insert時,得到一個異常SqlCeException「未指定的錯誤」。以下是我的代碼。任何提示?TableDirect表訪問SQL CE 3.5問題

感謝

public bool StoreEventsDB2(List<DAO.Event> events) 
    { 
     try 
     { 

      SqlCeCommand command = new SqlCeCommand("Event"); 
      command.CommandType = System.Data.CommandType.TableDirect; 

      SqlCeResultSet rs = _databaseManager.ExecuteResultSet(command, ResultSetOptions.Updatable | ResultSetOptions.Scrollable); 

      foreach (DAO.Event theEvent in events) 
      { 
       SqlCeUpdatableRecord record = rs.CreateRecord(); 
       record.SetInt32(0, theEvent.ID); 
       record.SetInt32(1, theEvent.ParentID); 
       record.SetString(2, theEvent.Name); 
       record.SetDateTime(3, theEvent.DateTime); 

       record.SetDateTime(4, theEvent.LastSynced); 
       record.SetInt32(5, theEvent.LastSyncedTS); 

       record.SetString(6, theEvent.VenueName); 
       record.SetBoolean(7, theEvent.IsParentEvent); 

       record.SetDateTime(11, DateTime.Now); 

       rs.Insert(record); 
      } 

     } 
     catch (SqlCeException e) 
     { 
      Log.Logger.GetLogger().Log(Log.Logger.LogLevel.ERROR, "[EventManager::StoreEventsDB] error: {0}", e.Message); 
      return false; 
     } 
     catch (Exception e) 
     { 
      Log.Logger.GetLogger().Log(Log.Logger.LogLevel.ERROR, "[EventManager::StoreEventsDB] error: {0}", e.Message); 
      return false; 
     } 
     return true; 
    } 

回答

0

我不確定如何您的連接與它可能是罪魁禍首數據庫管理器管理 - 確保你正在使用一個連接(SQLCE沒有發揮好)。此外,結果集選項「ResultSetOption.Scrollable」是不需要的(至少我從來沒有使用它插入)。

下面是我在做直接表插入時使用的語法。每個數據庫/數據訪問對象都被包裝在一個using語句中,以便在使用後處理對象 - 這對於緊湊框架和sqlce非常重要,因爲垃圾回收並不理想(您將會遇到內存不足異常!)。我還爲您的代碼添加了一個事務,以便該選項全部或全部不變。

希望這有助於:

using (var transaction = connection.BeginTransaction()) 
{ 
    using (var command = connection.CreateCommand()) 
    { 
     command.Transaction = transaction; 
     command.CommandType = CommandType.TableDirect; 
     command.CommandText = "Event"; 

     using (var rs = command.ExecuteResultSet(ResultSetOptions.Updatable)) 
     { 
      var record = rs.CreateRecord(); 

      foreach (DAO.Event theEvent in events) 
      { 
       record.SetInt32(0, theEvent.ID); 
       record.SetInt32(1, theEvent.ParentID); 
       record.SetString(2, theEvent.Name); 
       record.SetDateTime(3, theEvent.DateTime); 
       record.SetDateTime(4, theEvent.LastSynced); 
       record.SetInt32(5, theEvent.LastSyncedTS); 
       record.SetString(6, theEvent.VenueName); 
       record.SetBoolean(7, theEvent.IsParentEvent); 
       record.SetDateTime(11, DateTime.Now); 
       rs.Insert(record); 
      } 
     } 
     transaction.Commit(); 
    } 
}