当前位置:网站首页>C#访问SQL Server数据库两种方式的比较(SqlDataReader vs SqlDataAdapter)
C#访问SQL Server数据库两种方式的比较(SqlDataReader vs SqlDataAdapter)
2022-06-30 08:36:00 【皓月如我】
1.使用SqlDataReader读数据
public bool CheckResultFromDatabase(string guid)
{
string connStr = "Data Source = localhost; Initial Catalog = TestDB; User ID = sa; Password = Abc12345";
// Create connection
SqlConnection Myconnect = new SqlConnection(connStr);
Myconnect.Open();
// Build up query
StringBuilder sb = new StringBuilder();
sb.Append($"select id, name from dbo.table_a where id = '{
guid}';");
sb.Append($"select student_id, student_name from dbo.student where student_name = 'zhangsan';");
string sql = sb.ToString();
SqlCommand sqlQuery = new SqlCommand(sql, Myconnect);
int rowCount = 0;
bool [] checkresult = {
false, false };
int expectedResultNum = 2;
int currentResult = 0;
using (SqlDataReader reader = sqlQuery.ExecuteReader())
{
do
{
rowCount = 0;
while (reader.Read())
{
rowCount++;
}
if (rowCount == 1)
{
checkresult[currentResult++] = true;
if (currentResult == expectedResultNum)
break;
}
} while (reader.NextResult()); // go to result of next sql query
reader.Close();
}
Myconnect.Close(); // close databse
return checkresult[0] && checkresult[1];
}
2.使用SqlDataReader读数据
public bool CheckResultFromDatabaseAdapter(string guid)
{
string connStr = "Data Source = localhost; Initial Catalog = TestDB; User ID = sa; Password = Abc12345";
bool resultConfig = false;
bool resultSummary = false;
using (SqlConnection conn = new SqlConnection(connStr))
{
string strSql = $"select id, name from dbo.table_a where id = '{
guid}';";
using (SqlDataAdapter adapter = new SqlDataAdapter(strSql, conn))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows.Count == 1)
{
resultConfig = true;
}
//dt.Rows[0][1] //1st record 1st row
//foreach (DataRow dataRow in dt.Rows)
//{
// Console.WriteLine(dataRow["SimulationId"]);
//}
}
strSql = $"select student_id, student_name from dbo.student where student_name = 'zhangsan';";
using (SqlDataAdapter adapter = new SqlDataAdapter(strSql, conn))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows.Count == 1)
{
resultSummary = true;
}
}
}
return resultConfig & resultSummary;
}
3. 两种方法的对比
上面的两段代码,功能相同,即:从两张表中读取符合某一条件的数据,如果各自的记录数都为1,则返回true,否则返回false。
SqlDataReader的特点是:
- 多个查询可以一次性做完,也必须一次性做完。统一返回再通过NextResult()来切换到下一个结果集。这样最显著的好处是减少了client和db server的交互次数,某些情况下能大幅提高程序的效率。
- 没有RowCount属性或方法,如果要知道某一个结果集中记录的条数,只能遍历以后再自行统计。总之,不太友好。
说完前者,SqlDataAdapter的特点自然就显现出来了:
- 接口丰富,对编程者而言,方便许多。
- 可以多次查询,有助于提高程序的易读性。
边栏推荐
- Viteproject require Syntax Compatibility Problem Solving require is not defined
- 【NVMe2.0b 14】NVMe Admin Command Set
- Detectron2 source code reading 2--- using the configurable decorator to build the dataloader
- Sword finger offer II 075 Array relative sort (custom sort, count sort)
- End-to-end 3D Point Cloud Instance Segmentation without Detection
- Detailed explanation of pytoch's scatter function
- Transformer architecture understanding
- JS中的this指向
- 酒精测试仪方案:酒精测试仪是根据什么原理测酒精溶度?
- 增强for循环的增删操作 & 迭代器删除集合元素
猜你喜欢

Wsl2 using GPU for deep learning

Redis design and Implementation (II) | database (deletion strategy & expiration elimination strategy)

vim 从嫌弃到依赖(21)——跨文件搜索

Cesium learning notes (VI) particle system

Redis design and Implementation (III) | interaction between server and client (event IO model)

2021-04-29

Build a docker image of Henkel database from 0

Enhance the add / delete operation of for loop & iterator delete collection elements
![[untitled]](/img/b8/e3f54fe5d1079663799887e62cb07c.jpg)
[untitled]

【NVMe2.0b 14-6】Format NVM、Keep Alive、Lockdown command
随机推荐
技术管理进阶——管理者如何进行梯队设计及建设
Sword finger offer II 074 Merge interval (sort, array)
Redis design and Implementation (VI) | cluster (sharding)
Viteproject require Syntax Compatibility Problem Solving require is not defined
国债逆回购绝对安全吗 网上怎么开户
【NVMe2.0b 14-2】Create/Delete Queue
Using typera+picgo to realize automatic uploading of markdown document pictures
How can we get a satisfactory salary? These routines still need to be mastered
swagger使用
Swagger use
2021-02-27
【NVMe2.0b 14-7】Set Features(上篇)
mysql基础入门 day4 动力节点[老杜]课堂笔记
layer.open 当传值为数组或值太长时处理方法
A troubleshooting of CPU bottom falling
维基媒体基金会公布新商业产品“维基媒体企业”首批客户
File upload component on success event, add custom parameters
Gilbert Strang's course notes on linear algebra - Lesson 1
Unit Test
【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command