当前位置:网站首页>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的特點自然就顯現出來了:
- 接口豐富,對編程者而言,方便許多。
- 可以多次查詢,有助於提高程序的易讀性。
边栏推荐
- Flink 数据偶尔数据积压导致checkpoint失败
- [untitled]
- MIME类型大全
- Axure make menu bar effect
- layer. Open processing method when the passed value is an array or the value is too long
- Getordefault method of map class
- 【NVMe2.0b 14-5】Firmware Download/Commit command
- El input limit can only input numbers
- Map,String,Json之間轉換
- Dlib database face
猜你喜欢

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

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

What are the Amazon evaluation terms?

Deploy the cow like customer network project on the ECS

Redis design and Implementation (VI) | cluster (sharding)

Redis design and Implementation (VII) | publish & subscribe

自制GIF动态图-gifcam

一次cpu 跌底排查

Flink 数据偶尔数据积压导致checkpoint失败

Redis设计与实现(五)| Sentinel哨兵
随机推荐
Circuit analysis of current probe
Cesium learning notes (II) uploading data using rest API
VIM from dislike to dependence (21) -- cross file search
[untitled]
Cesium learning notes (III) creating instances
Redis design and Implementation (III) | interaction between server and client (event IO model)
酒精测试仪方案:酒精测试仪是根据什么原理测酒精溶度?
Interference source current spectrum test of current probe
Introduction to MySQL foundation power node [Lao Du] class assignment
El input limit can only input numbers
Dlib database face
Flink sql -- No factory implements ‘org.apache.flink.table.delegation.ExecutorFactory‘.
Mmcv expanding CUDA operator beginner level chapter
Redis设计与实现(五)| Sentinel哨兵
Cesium learning notes (VI) particle system
MIME类型大全
Flink Exception -- No ExecutorFactory found to execute the application
示波器探头对测量电容负荷有影响吗?
Flink 数据偶尔数据积压导致checkpoint失败
codeforces每日5题(均1700)-第三天