場景
新建一個程式,需要對資料的表進行查詢并將查詢結果轉換為物體類,然后將多個物體類
再插入到另一個資料庫的表中,執行插入的程序中要使用事務,
注:
博客主頁:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程式猿
獲取編程相關電子書、教程推送與免費下載,
實作
不帶事務只是查詢
//儲存資料的工具初始化 DataSet idxDs = new DataSet(); //constr:資料庫連接字串配置 stringconstr="server=localhost;database=Badao;uid=sa;pwd=123"; using (SqlConnection conn=new SqlConnection(constr)) { conn.Open(); Console.WriteLine("開始查詢索引資料..."); //查詢索引資料 string idxSql = "SELECT * FROM Idx1_1";//獲取sql陳述句 SqlDataAdapter idxSda = new SqlDataAdapter(idxSql, conn); //(查詢陳述句和連接工具) idxSda.Fill(idxDs); //將配接器資料存入DataSet工具中 }
注:
首先宣告一個DataSet用來存盤執行查詢的結果,然后使用連接資料的字串打開連接,
然后使用Adapter執行sql陳述句,將查詢結果填充到Dataset中,
怎樣將查詢結果與物體類對應賦值
IdxRecord idx = null; Console.WriteLine("開始儲存索引資料..."); foreach (DataRow row in idxDs.Tables[0].Rows) { idx = new IdxRecord(); idx.IdxID = DataProcessor.RowValue(row, "Idx_ID", 0); idx.DataPoint = DataProcessor.RowValue(row, "Data_Point", 0); idx.ScheduleIndex = DataProcessor.RowValue(row, "Schedule_Index", 0L); idxList.Add(idx); }
注:
宣告一個物體類,其中要有與資料庫列所對應的欄位,
然后將DataSet中的內容與物體列的屬性一一賦值,
最后將物體類物件添加到物體類的list上,
其中DataProcessor.RowValue是一個工具類中的方法,此方法中的第二個引數是對應的資料庫中的列
public static short RowValue(DataRow dr, string field, short defaultValue) { short Result = defaultValue; if (dr.Table.Columns.Contains(field)) { if (dr[field] != null && dr[field] != DBNull.Value) { if (short.TryParse(dr[field].ToString(), out Result)) { return Result; } } } else { Console.WriteLine("DataTable中不存在[" + field + "]列!"); } return defaultValue; }
怎樣開啟事務并存入資料
//存入bak資料庫 stringconstrBak="server=localhost;database=BadaoBak;uid=sa;pwd=123"; using (SqlConnection conn = new SqlConnection(constrBak))//constr:資料庫連接配置 { conn.Open(); //開啟事務 SqlTransaction trans = conn.BeginTransaction(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn;//添加連接工具 cmd.Transaction = trans;//添加事務 try { cmd.CommandText = "INSERT INTO idx1_1 values ('" + idx.IdxID + "','" + idx.StepEnd +"')";//添加sql陳述句 cmd.ExecuteNonQuery();//執行 Console.WriteLine("插入索引資料成功"); trans.Commit();//執行完成之后提交 } catch (Exception e) { //執行sql陳述句失敗,事務回滾 trans.Rollback(); } finally { conn.Close(); } }
完整示例代碼
public static void Main(string[] args) { List<IdxRecord> idxList = null; //索引資料 //儲存資料的工具初始化 DataSet idxDs = new DataSet(); //constr:資料庫連接字串配置 string constr = "server=localhost;database=Badao;uid=sa;pwd=123"; using (SqlConnection conn=new SqlConnection(constr)) { conn.Open(); Console.WriteLine("開始查詢索引資料..."); //查詢索引資料 string idxSql = "SELECT * FROM Idx1_1";//獲取sql陳述句 SqlDataAdapter idxSda = new SqlDataAdapter(idxSql, conn); //(查詢陳述句和連接工具) idxSda.Fill(idxDs); //將配接器資料存入DataSet工具中 idxList = new List<IdxRecord>(); IdxRecord idx = null; Console.WriteLine("開始儲存索引資料..."); foreach (DataRow row in idxDs.Tables[0].Rows) { idx = new IdxRecord(); idx.IdxID = DataProcessor.RowValue(row, "Idx_ID", 0); idxList.Add(idx); } Console.WriteLine("儲存索引資料成功,成功儲存數量為:" + idxList.Count); Console.WriteLine("查詢索引資料成功"); Console.WriteLine("開始根據索引資料查詢記錄資料..."); //在回圈中根據索引資料查詢記錄資料 for (int i = 0; i+1 < idxList.Count;i++) { List<Record> recordList = new List<Record>(); List<List<AuxRecord>> autxRecordsList = new List<List<AuxRecord>>(); for (int k = idxList[i].DataPoint; k < idxList[i + 1].DataPoint;k++ ) { DataSet recordsDs = new DataSet(); DataSet auxTDs = new DataSet(); //查詢 記錄資料 string recordSql = "SELECT * FROM WsC1_1 where Data_Point =" + k;//獲取sql陳述句 //Console.WriteLine("開始執行的查詢陳述句為:" + recordSql); SqlDataAdapter recordsSda = new SqlDataAdapter(recordSql, conn); //(查詢陳述句和連接工具) recordsSda.Fill(recordsDs); //將配接器資料存入DataSet工具中 Record entity = new Record(); DataRow row = recordsDs.Tables[0].Rows[0]; entity.DataPoint = DataProcessor.RowValue(row, "Data_Point", 0); entity.ScheduleIndex = DataProcessor.RowValue(row, "Schedule_Index", 0L); recordList.Add(entity); //Console.WriteLine("根據索引資料的DataPoint:" + k + "查詢到的記錄資料的DataPoint:" + entity.DataPoint); //根據索引資料查詢輔助通道溫度資料 Console.WriteLine("開始根據記錄資料查詢輔助通道溫度資料...."); List<AuxRecord> autxRecords = new List<AuxRecord>(); //輔助通道溫度資料 string AuxTSql = "SELECT * FROM Aux1_1_25 where IvIndex =" + entity.AuxIndex;//獲取sql陳述句 SqlDataAdapter AuxTSda = new SqlDataAdapter(AuxTSql, conn); //(查詢陳述句和連接工具) AuxTSda.Fill(auxTDs); //將配接器資料存入DataSet工具中 //autxRecords = new List<AuxRecord>(); AuxRecord aux = null; foreach (DataRow auxrow in auxTDs.Tables[0].Rows) { aux = new AuxRecord(); aux.DataPoint = DataProcessor.RowValue(auxrow, "Data_Point", 0); aux.IvIndex = DataProcessor.RowValue(auxrow, "IvIndex", 0); foreach (DataColumn col in auxTDs.Tables[0].Columns) { if (col.ColumnName.StartsWith("T") || col.ColumnName.StartsWith("V")) { aux.Data.Add(DataProcessor.RowValue(row, col.ColumnName, 0D)); } } autxRecords.Add(aux); } autxRecordsList.Add(autxRecords); Console.WriteLine("根據記錄資料查詢輔助通道溫度資料成功"); } //conn.Close(); //開始向資料庫插入中傳遞引數 bool isStoreSuccess = StoreRecordData(idxList[i],recordList,autxRecordsList); if (isStoreSuccess) { Console.WriteLine("存入資料庫成功"); } else { Console.WriteLine("存入資料庫失敗"); } //開始休眠 Console.WriteLine("開始休眠..."); System.Threading.Thread.Sleep(1000 * 5);// Console.WriteLine("休眠結束..."); } //Console.WriteLine("查詢輔助通道溫度資料成功"); //Console.ReadKey(); } } public static bool StoreRecordData(IdxRecord idx, List<Record> recordList, List<List<AuxRecord>> autxRecordsList) { //存入bak資料庫 string constrBak = "server=localhost;database=BadaoBak;uid=sa;pwd=123"; using (SqlConnection conn = new SqlConnection(constrBak))//constr:資料庫連接配置 { conn.Open(); //開啟事務 SqlTransaction trans = conn.BeginTransaction(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn;//添加連接工具 cmd.Transaction = trans;//添加事務 try { cmd.CommandText = "INSERT INTO idx1_1 values ('" + idx.IdxID + "','" + idx.DataPoint + "','" + idx.StepEnd +"')";//添加sql陳述句 cmd.ExecuteNonQuery();//執行 Console.WriteLine("插入索引資料成功"); foreach(Record record in recordList) { cmd.CommandText = "INSERT INTO WsC1_1 values ('" + record.DataPoint + "','" + record.ScheduleIndex + "','" + record.AuxIndex + "')";//添加sql陳述句 cmd.ExecuteNonQuery();//執行 } Console.WriteLine("插入記錄資料成功"); foreach (List<AuxRecord> auxRecords in autxRecordsList) { cmd.CommandText = "INSERT INTO Aux1_1_25 values ('" + auxRecords[0].DataPoint + "','" + auxRecords[0].IvIndex + "','" + auxRecords[0].Data[0] + "')";//添加sql陳述句 cmd.ExecuteNonQuery();//執行 } Console.WriteLine("插入輔助通道溫度資料成功"); trans.Commit();//執行完成之后提交 return true; } catch (Exception e) { //執行sql陳述句失敗,事務回滾 trans.Rollback(); return false; } finally { conn.Close(); } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/93234.html
標籤:C#
上一篇:[譯]C# 7系列,Part 4: Discards 棄元
下一篇:C#程式撰寫高質量代碼改善的157個建議【10-12】[創建物件時需要考慮是否實作比較器、區別對待==和Equals]
