C#中怎樣連接數據庫並將查詢結果轉為實體類以及如何加入事務


場景

新建一個程序,需要對數據的表進行查詢並將查詢結果轉換為實體類,然后將多個實體類

再插入到另一個數據庫的表中,執行插入的過程中要使用事務。

注:

博客主頁:
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();

                }
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM