当前位置:网站首页>Comparaison de deux façons d'accéder à la base de données SQL Server (sqldatareader vs sqldataadapter)
Comparaison de deux façons d'accéder à la base de données SQL Server (sqldatareader vs sqldataadapter)
2022-06-30 08:37:00 【La lune est comme moi.】
1.UtiliserSqlDataReaderLire les données
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.UtiliserSqlDataReaderLire les données
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. Comparaison des deux méthodes
Les deux codes ci - dessus,Même fonction,C'est - à - dire:: Lire à partir de deux tableaux les données correspondant à une condition , Si le nombre d'enregistrements respectifs est 1,Renvoietrue,Sinon, retournez àfalse.
SqlDataReaderLa caractéristique de:
- Plusieurs requêtes peuvent être faites en même temps , Doit également être fait en même temps . Unified Return and pass NextResult() Pour passer à l'ensemble de résultats suivant . L'avantage le plus important de cette réduction est clientEtdb serverNombre d'interactions pour, Dans certains cas, l'efficacité des procédures peut être considérablement améliorée .
- Non.RowCountPropriétés ou méthodes, Si vous voulez connaître le nombre d'enregistrements dans un ensemble de résultats , Vous ne pouvez faire vos propres statistiques qu'après avoir traversé .En dernier analyse,Pas très amical..
Finis le premier. ,SqlDataAdapter Les caractéristiques de :
- Interface riche, Pour les programmeurs ,Beaucoup plus pratique.
- Peut être interrogé plus d'une fois , Aide à améliorer la lisibilité du programme .
边栏推荐
- Redis design and Implementation (III) | interaction between server and client (event IO model)
- [untitled]
- CUDA realizes matrix multiplication
- 【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command
- 【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command
- Redis design and Implementation (VII) | publish & subscribe
- 电流探头电路分析
- Redis design and Implementation (V) | sentinel sentry
- Detectron2 source code reading 2--- using the configurable decorator to build the dataloader
- C# ListBox如何获取选中的内容(搜了很多无效的文章)
猜你喜欢

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

涂鸦Wi-Fi&BLE SoC开发幻彩灯带

【NVMe2.0b 14-2】Create/Delete Queue

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

Using typera+picgo to realize automatic uploading of markdown document pictures

A troubleshooting of CPU bottom falling

Self made GIF dynamic graph -gifcam

Cesium learning notes (III) creating instances

What are the Amazon evaluation terms?

Detectron2 source code reading 4-- registrar construction model
随机推荐
Flink sql -- No factory implements ‘org.apache.flink.table.delegation.ExecutorFactory‘.
layer.open 当传值为数组或值太长时处理方法
Wechat official account third-party platform development, zero foundation entry. I want to teach you
自制GIF动态图-gifcam
Deploy the cow like customer network project on the ECS
【NVMe2.0b 14-4】Directive Send/Receive command
2021-02-18
Map,String,Json之間轉換
mysql基础入门 day3 动力节点[老杜]课堂笔记
【NVMe2.0b 14】NVMe Admin Command Set
Detectron2 source code reading 4-- registrar construction model
启动jar包报错UnsupportedClassVersionError,如何修复
Redis设计与实现(四)| 主从复制
维基媒体基金会公布新商业产品“维基媒体企业”首批客户
【NVMe2.0b 14-5】Firmware Download/Commit command
Be careful of this hole in transmittable thread local
Interference source current spectrum test of current probe
Flink Exception -- No ExecutorFactory found to execute the application
Redis design and Implementation (VI) | cluster (sharding)
小心transmittable-thread-local的这个坑