当前位置:网站首页>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的特点自然就显现出来了:
- 接口丰富,对编程者而言,方便许多。
- 可以多次查询,有助于提高程序的易读性。
边栏推荐
- 2021-02-22
- Redis设计与实现(三)| 服务器与客户端的交互(事件IO模型)
- 【NVMe2.0b 14-2】Create/Delete Queue
- Redis设计与实现(六)| 集群(分片)
- 【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command
- Introduction to MySQL basics day4 power node [Lao Du] class notes
- Build a docker image of Henkel database from 0
- El input limit can only input numbers
- This point in JS
- Detectron2 source code reading 2--- using the configurable decorator to build the dataloader
猜你喜欢
电流探头的干扰源电流谱测试
【NVMe2.0b 14-5】Firmware Download/Commit command
微信公众号第三方平台开发,零基础入门。想学我教你啊
Sword finger offer II 074 Merge interval (sort, array)
Redis设计与实现(五)| Sentinel哨兵
Wsl2 using GPU for deep learning
Redis设计与实现(一)| 数据结构 & 对象
Codeworks 5 questions per day (1700 for each) - the third day
电流探头电路分析
Redis design and Implementation (V) | sentinel sentry
随机推荐
Cesium learning notes (IV) visual image & Terrain
Redis设计与实现(五)| Sentinel哨兵
示波器探头对测量电容负荷有影响吗?
2021-04-29
layer. Open processing method when the passed value is an array or the value is too long
CUDA realizes matrix multiplication
Viteproject require Syntax Compatibility Problem Solving require is not defined
Cesium learning notes (I)
Summary of common pytoch APIs
Common tools installation, configuration, compilation, link, etc
End-to-end 3D Point Cloud Instance Segmentation without Detection
Gilbert Strang's course notes on linear algebra - Lesson 2
Leetcode47. full arrangement II
Deploy the cow like customer network project on the ECS
Dlib library blink
Opencv video
Source code interpretation of detectron2 1--engine
Flink sql -- No factory implements ‘org.apache.flink.table.delegation.ExecutorFactory‘.
[nvme2.0b 14 - 5] commande de téléchargement / commande du logiciel
2021-02-22