当前位置:网站首页>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的特点自然就显现出来了:
- 接口丰富,对编程者而言,方便许多。
- 可以多次查询,有助于提高程序的易读性。
边栏推荐
- Oracle expansion table space installed in docker
- Axure make menu bar effect
- [kotlin collaboration process] complete the advanced kotlin collaboration process
- Cesium learning notes (II) uploading data using rest API
- Detectron2 source code reading 4-- registrar construction model
- Unit Test
- 2021-02-18
- Getordefault method of map class
- 2021-05-17
- CUDA realizes matrix multiplication
猜你喜欢

Cesium learning notes (V) custom geometry and appearance

End-to-end 3D Point Cloud Instance Segmentation without Detection

【NVMe2.0b 14-6】Format NVM、Keep Alive、Lockdown command

swagger使用

Graffiti Wi Fi & ble SoC development slide strip

电流探头电路分析

Redis design and Implementation (VIII) | transaction

【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command

1. Problems related to OpenGL window and environment configuration

Flink 数据偶尔数据积压导致checkpoint失败
随机推荐
Unit Test
【NVMe2.0b 14-5】Firmware Download/Commit command
2021-02-22
Redis设计与实现(二)| 数据库(删除策略&过期淘汰策略)
[untitled]
Redis设计与实现(五)| Sentinel哨兵
Redis设计与实现(八)| 事务
[data analysis and display]
[untitled]
PHP API to obtain QR code and combine to generate pictures
Sword finger offer II 074 Merge interval (sort, array)
Be careful of this hole in transmittable thread local
Vite project require syntax compatibility problem solving require is not defined
El input limit can only input numbers
示波器探头对测量电容负荷有影响吗?
Cesium learning notes (V) custom geometry and appearance
Understanding society at the age of 14 - reading notes on "happiness at work"
增强for循环的增删操作 & 迭代器删除集合元素
How can we get a satisfactory salary? These routines still need to be mastered
【NVMe2.0b 14-3】Doorbell Buffer Config command、Device Self-test command