標籤:複製 服務 manager adt foreach data length ppi date
/// <summary> /// 上傳本地資訊至伺服器 /// </summary> public static void UploadDataToServer() { try { #region 1.讀取本機資料 StringBuilder sbSelect = new StringBuilder(); foreach (string tblName in CMMConstants.UPLOADTABLENAMES) { // 查詢未上傳的資料 sbSelect.Append(string.Format(" SELECT * FROM {0} WHERE IsUpload=‘0‘ OR IsUpload IS NULL;", tblName)); } SQLiteDBManager _SQLiteDBManager = new SQLiteDBManager(); DataSet ds = _SQLiteDBManager.GetDataSet(sbSelect.ToString(), null); for (int i = 0; i < CMMConstants.UPLOADTABLENAMES.Length; i++) { // 設定DataTableName ds.Tables[i].TableName = CMMConstants.UPLOADTABLENAMES[i]; } #endregion #region 2.上傳至伺服器 // 伺服器資料訪問 DBManager _DBManager = new DBManager(); // 擷取伺服器表的欄位列表 DataSet dsColumns = _DBManager.GetColumns(CMMConstants.UPLOADTABLENAMES.ToList()); List<SqlBulkCopyColumnMapping> mappingCollection = null; DataTable dtTemp = null; DataTable dtData = null; DataTable dtCopy = null; string sColumnName = null; // 轉換guid列類型及複製資料表資料 Func<DataTable> setType = () => { // 需要設定成guid類型的列名集合 string[] columnNames = new string[] { "ShiYongID", "ShiYanShiID", "ZuoWeiID", "ShiYongMingXiID", "ShuKaJiLuID" }; DataTable dtSetType = dtData.Clone(); foreach (string columnName in columnNames) { if (dtSetType.Columns.Contains(columnName)) { // 設定列類型 dtSetType.Columns[columnName].DataType = typeof(Guid); } } // 填充資料 dtSetType.Load(dtData.CreateDataReader()); return dtSetType; }; // 迴圈多張表 foreach (string tblName in CMMConstants.UPLOADTABLENAMES) { dtData = ds.Tables[tblName]; dtTemp = dsColumns.Tables[tblName]; mappingCollection = new List<SqlBulkCopyColumnMapping>(); if (dtData.Rows.Count > 0) { // 迴圈表中的列集合 foreach (DataRow row in dtTemp.Rows) { sColumnName = row["name"].ToString(); if (dtData.Columns.Contains(sColumnName)) { // 添加映射 mappingCollection.Add(new SqlBulkCopyColumnMapping(sColumnName, sColumnName)); } } // 擷取轉換列類型後的資料表 dtCopy = setType(); // 將資料更新到伺服器 _DBManager.BulkCopy(tblName, dtCopy, mappingCollection); // 更新本機資料上傳狀態 string sKeyName = CMMConstants.UPLOADTABLENAMES_PrimaryKey[tblName]; string sInStr = InStr(dtCopy, sKeyName); string sUpdateSql = string.Format("UPDATE {0} SET IsUpload=‘{1}‘ where {2} IN({3})", tblName, "1", sKeyName, sInStr); int iResult = _SQLiteDBManager.ExeSql(sUpdateSql); } } #endregion } catch (Exception ex) { throw ex; } }
ps:
未加func處理datatable前,報string轉guid異常,直接修改datatable列類型報異常有資料時無法更改列類型,
func處理也許並不是最好的,將bulkcopy改為使用自訂表格類型,將資料傳遞到伺服器再進行寫入也許更好。
將Sqlite資料寫入Sqlserver