C#中怎样连接数据库并将查询结果转为实体类以及如何加入事务

场景

新建一个程序,需要对数据的表进行查询并将查询结果转换为实体类,然后将多个实体类

再插入到另一个数据库的表中,执行插入的过程中要使用事务。

注:

博客主页:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

不带事务只是查询

1//储存数据的工具初始化 2 DataSet idxDs = new DataSet(); 3 //constr:数据库连接字符串配置 4 stringconstr="server=localhost;database=Badao;uid=sa;pwd=123"; 5 using (SqlConnection conn=new SqlConnection(constr)) 6 7 { 8 9 conn.Open(); 10 Console.WriteLine("开始查询索引数据..."); 11 //查询索引数据 12 string idxSql = "SELECT * FROM Idx1_1";//获取sql语句 13 SqlDataAdapter idxSda = new SqlDataAdapter(idxSql, conn); //(查询语句和连接工具) 14 idxSda.Fill(idxDs); //将适配器数据存入DataSet工具中 15 }

注:

首先声明一个DataSet用来存储执行查询的结果,然后使用连接数据的字符串打开连接。

然后使用Adapter执行sql语句,将查询结果填充到Dataset中。

怎样将查询结果与实体类对应赋值

1IdxRecord idx = null; 2 Console.WriteLine("开始储存索引数据..."); 3 foreach (DataRow row in idxDs.Tables[0].Rows) 4 { 5 idx = new IdxRecord(); 6 idx.IdxID = DataProcessor.RowValue(row, "Idx_ID", 0); 7 idx.DataPoint = DataProcessor.RowValue(row, "Data_Point", 0); 8 idx.ScheduleIndex = DataProcessor.RowValue(row, "Schedule_Index", 0L); 9 idxList.Add(idx); 10 }

注:

声明一个实体类,其中要有与数据库列所对应的字段。

然后将DataSet中的内容与实体列的属性一一赋值。

最后将实体类对象添加到实体类的list上。

其中DataProcessor.RowValue是一个工具类中的方法,此方法中的第二个参数是对应的数据库中的列

1public static short RowValue(DataRow dr, string field, short defaultValue) 2 { 3 short Result = defaultValue; 4 if (dr.Table.Columns.Contains(field)) 5 { 6 if (dr[field] != null && dr[field] != DBNull.Value) 7 { 8 if (short.TryParse(dr[field].ToString(), out Result)) 9 { 10 return Result; 11 } 12 } 13 } 14 else 15 { 16 Console.WriteLine("DataTable中不存在[" + field + "]列!"); 17 } 18 return defaultValue; 19 }

怎样开启事务并存入数据

1//存入bak数据库 2 stringconstrBak="server=localhost;database=BadaoBak;uid=sa;pwd=123"; 3 using (SqlConnection conn = new SqlConnection(constrBak))//constr:数据库连接配置 4 { 5 conn.Open(); 6 //开启事务 7 SqlTransaction trans = conn.BeginTransaction(); 8 SqlCommand cmd = new SqlCommand(); 9 cmd.Connection = conn;//添加连接工具 10 cmd.Transaction = trans;//添加事务 11 try 12 { 13 cmd.CommandText = "INSERT INTO idx1_1 values ('" + idx.IdxID + "','" + idx.StepEnd +"')";//添加sql语句 14 cmd.ExecuteNonQuery();//执行 15 Console.WriteLine("插入索引数据成功"); 16 trans.Commit();//执行完成之后提交 17 18 19 } 20 catch (Exception e) 21 { 22 //执行sql语句失败,事务回滚 23 trans.Rollback(); 24 25 26 } 27 finally 28 { 29 conn.Close(); 30 31 } 32 }

完整示例代码

1public static void Main(string[] args) 2 { 3 List<IdxRecord> idxList = null; //索引数据 4 //储存数据的工具初始化 5 DataSet idxDs = new DataSet(); 6 //constr:数据库连接字符串配置 7 string constr = "server=localhost;database=Badao;uid=sa;pwd=123"; 8 using (SqlConnection conn=new SqlConnection(constr)) 9 { 10 conn.Open(); 11 Console.WriteLine("开始查询索引数据..."); 12 //查询索引数据 13 string idxSql = "SELECT * FROM Idx1_1";//获取sql语句 14 SqlDataAdapter idxSda = new SqlDataAdapter(idxSql, conn); //(查询语句和连接工具) 15 idxSda.Fill(idxDs); //将适配器数据存入DataSet工具中 16 idxList = new List<IdxRecord>(); 17 IdxRecord idx = null; 18 Console.WriteLine("开始储存索引数据..."); 19 foreach (DataRow row in idxDs.Tables[0].Rows) 20 { 21 idx = new IdxRecord(); 22 idx.IdxID = DataProcessor.RowValue(row, "Idx_ID", 0); 23 24 idxList.Add(idx); 25 } 26 Console.WriteLine("储存索引数据成功,成功储存数量为:" + idxList.Count); 27 Console.WriteLine("查询索引数据成功"); 28 Console.WriteLine("开始根据索引数据查询记录数据..."); 29 //在循环中根据索引数据查询记录数据 30 for (int i = 0; i+1 < idxList.Count;i++) 31 { 32 List<Record> recordList = new List<Record>(); 33 List<List<AuxRecord>> autxRecordsList = new List<List<AuxRecord>>(); 34 for (int k = idxList[i].DataPoint; k < idxList[i + 1].DataPoint;k++ ) 35 { 36 DataSet recordsDs = new DataSet(); 37 DataSet auxTDs = new DataSet(); 38 //查询 记录数据 39 string recordSql = "SELECT * FROM WsC1_1 where Data_Point =" + k;//获取sql语句 40 //Console.WriteLine("开始执行的查询语句为:" + recordSql); 41 SqlDataAdapter recordsSda = new SqlDataAdapter(recordSql, conn); //(查询语句和连接工具) 42 recordsSda.Fill(recordsDs); //将适配器数据存入DataSet工具中 43 Record entity = new Record(); 44 DataRow row = recordsDs.Tables[0].Rows[0]; 45 entity.DataPoint = DataProcessor.RowValue(row, "Data_Point", 0); 46 entity.ScheduleIndex = DataProcessor.RowValue(row, "Schedule_Index", 0L); 47 48 recordList.Add(entity); 49 //Console.WriteLine("根据索引数据的DataPoint:" + k + "查询到的记录数据的DataPoint:" + entity.DataPoint); 50 51 //根据索引数据查询辅助通道温度数据 52 Console.WriteLine("开始根据记录数据查询辅助通道温度数据...."); 53 List<AuxRecord> autxRecords = new List<AuxRecord>(); //辅助通道温度数据 54 string AuxTSql = "SELECT * FROM Aux1_1_25 where IvIndex =" + entity.AuxIndex;//获取sql语句 55 SqlDataAdapter AuxTSda = new SqlDataAdapter(AuxTSql, conn); //(查询语句和连接工具) 56 AuxTSda.Fill(auxTDs); //将适配器数据存入DataSet工具中 57 //autxRecords = new List<AuxRecord>(); 58 AuxRecord aux = null; 59 foreach (DataRow auxrow in auxTDs.Tables[0].Rows) 60 { 61 aux = new AuxRecord(); 62 aux.DataPoint = DataProcessor.RowValue(auxrow, "Data_Point", 0); 63 aux.IvIndex = DataProcessor.RowValue(auxrow, "IvIndex", 0); 64 foreach (DataColumn col in auxTDs.Tables[0].Columns) 65 { 66 if (col.ColumnName.StartsWith("T") || col.ColumnName.StartsWith("V")) 67 { 68 aux.Data.Add(DataProcessor.RowValue(row, col.ColumnName, 0D)); 69 } 70 } 71 autxRecords.Add(aux); 72 } 73 autxRecordsList.Add(autxRecords); 74 Console.WriteLine("根据记录数据查询辅助通道温度数据成功"); 75 76 77 } 78 //conn.Close(); 79 //开始向数据库插入中传递参数 80 bool isStoreSuccess = StoreRecordData(idxList[i],recordList,autxRecordsList); 81 if (isStoreSuccess) 82 { 83 Console.WriteLine("存入数据库成功"); 84 } 85 else 86 { 87 Console.WriteLine("存入数据库失败"); 88 } 89 //开始休眠 90 Console.WriteLine("开始休眠..."); 91 System.Threading.Thread.Sleep(1000 * 5);// 92 Console.WriteLine("休眠结束..."); 93 94 } 95 96 //Console.WriteLine("查询辅助通道温度数据成功"); 97 //Console.ReadKey(); 98 99 } 100 } 101 102 public static bool StoreRecordData(IdxRecord idx, List<Record> recordList, List<List<AuxRecord>> autxRecordsList) 103 { 104 //存入bak数据库 105 string constrBak = "server=localhost;database=BadaoBak;uid=sa;pwd=123"; 106 using (SqlConnection conn = new SqlConnection(constrBak))//constr:数据库连接配置 107 { 108 conn.Open(); 109 //开启事务 110 SqlTransaction trans = conn.BeginTransaction(); 111 SqlCommand cmd = new SqlCommand(); 112 cmd.Connection = conn;//添加连接工具 113 cmd.Transaction = trans;//添加事务 114 try 115 { 116 cmd.CommandText = "INSERT INTO idx1_1 values ('" + idx.IdxID + "','" + idx.DataPoint + "','" + idx.StepEnd +"')";//添加sql语句 117 cmd.ExecuteNonQuery();//执行 118 Console.WriteLine("插入索引数据成功"); 119 foreach(Record record in recordList) 120 { 121 cmd.CommandText = "INSERT INTO WsC1_1 values ('" + record.DataPoint + "','" + record.ScheduleIndex + "','" + record.AuxIndex + "')";//添加sql语句 122 cmd.ExecuteNonQuery();//执行 123 } 124 Console.WriteLine("插入记录数据成功"); 125 foreach (List<AuxRecord> auxRecords in autxRecordsList) 126 { 127 cmd.CommandText = "INSERT INTO Aux1_1_25 values ('" + auxRecords[0].DataPoint + "','" + auxRecords[0].IvIndex + "','" + auxRecords[0].Data[0] + "')";//添加sql语句 128 cmd.ExecuteNonQuery();//执行 129 } 130 Console.WriteLine("插入辅助通道温度数据成功"); 131 trans.Commit();//执行完成之后提交 132 return true; 133 134 } 135 catch (Exception e) 136 { 137 //执行sql语句失败,事务回滚 138 trans.Rollback(); 139 return false; 140 141 } 142 finally 143 { 144 conn.Close(); 145 146 } 147 } 148 }
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

sql注入

反引号是个比较特别的字符,下面记录下怎么利用0x00SQL注入反引号可利用在分隔符及注释作用,不过使用范围只于表名、数据库名、字段名、起别名这些场景,下面具体说下1)表名payload:select\from\users\whereuser\_id1limit0,1;!(https://o

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )