当前位置:网站首页>C#訪問SQL Server數據庫兩種方式的比較(SqlDataReader vs SqlDataAdapter)
C#訪問SQL Server數據庫兩種方式的比較(SqlDataReader vs SqlDataAdapter)
2022-06-30 08:37: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的特點自然就顯現出來了:
- 接口豐富,對編程者而言,方便許多。
- 可以多次查詢,有助於提高程序的易讀性。
边栏推荐
- [untitled]
- 2021-05-17
- End-to-end 3D Point Cloud Instance Segmentation without Detection
- 挖财开户安全吗?怎么有人说不靠谱。
- Redis design and Implementation (VIII) | transaction
- 【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command
- Environment configuration of ROS Aubo manipulator
- 增强for循环的增删操作 & 迭代器删除集合元素
- 【NVMe2.0b 14-3】Doorbell Buffer Config command、Device Self-test command
- VIM from dislike to dependence (21) -- cross file search
猜你喜欢
![[data analysis and display]](/img/86/19260ee664769c98588d8b0783ef28.jpg)
[data analysis and display]

Gilbert Strang's course notes on linear algebra - Lesson 3

Redis设计与实现(七)| 发布 & 订阅

2021-04-29

Sword finger offer II 076 The kth largest number in the array (use heap to solve TOPK problem)

Wikimedia Foundation announces the first customers of its new commercial product "Wikimedia enterprise"

Deploy the cow like customer network project on the ECS

【NVMe2.0b 14-3】Doorbell Buffer Config command、Device Self-test command

示波器探头对测量电容负荷有影响吗?

Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which
随机推荐
自制GIF动态图-gifcam
Redis design and Implementation (III) | interaction between server and client (event IO model)
Getordefault method of map class
Wikimedia Foundation announces the first customers of its new commercial product "Wikimedia enterprise"
Detailed explanation of pytoch's scatter function
Sword finger offer II 076 The kth largest number in the array (use heap to solve TOPK problem)
icon资源
【NVMe2.0b 14-6】Format NVM、Keep Alive、Lockdown command
TiDB 6.0:让 TSO 更高效丨TiDB Book Rush
【NVMe2.0b 14-4】Directive Send/Receive command
Graffiti Wi Fi & ble SoC development slide strip
How can we get a satisfactory salary? These routines still need to be mastered
Codeworks 5 questions per day (1700 for each) - the third day
[untitled]
layer.open 当传值为数组或值太长时处理方法
2021-02-19
示波器探头对测量电容负荷有影响吗?
vite項目require語法兼容問題解决require is not defined
C # listbox how to get the selected content (search many invalid articles)
[untitled]