当前位置:网站首页>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 .
边栏推荐
- CUDA realizes matrix multiplication
- Flink sql -- No factory implements ‘org.apache.flink.table.delegation.ExecutorFactory‘.
- 维基媒体基金会公布新商业产品“维基媒体企业”首批客户
- Source code interpretation of detectron2 1--engine
- How can we get a satisfactory salary? These routines still need to be mastered
- [untitled]
- Oracle expansion table space installed in docker
- Cesium learning notes (V) custom geometry and appearance
- Unity simple shader
- 我们如何拿到自己满意的薪资呢?这些套路还是需要掌握的
猜你喜欢

Transformer architecture understanding

【NVMe2.0b 14】NVMe Admin Command Set

Qt连接神通数据库

电流探头的干扰源电流谱测试

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

Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which

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

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

codeforces每日5题(均1700)-第三天

Redis设计与实现(四)| 主从复制
随机推荐
Tidb 6.0: making Tso more efficient tidb Book rush
Is the reverse repurchase of treasury bonds absolutely safe? How to open an account online
MIME type Encyclopedia
维基媒体基金会公布新商业产品“维基媒体企业”首批客户
[untitled]
2021-02-22
Game 280 problem2: minimum operands to turn an array into an alternating array
What are the Amazon evaluation terms?
Common tools installation, configuration, compilation, link, etc
Introduction to MySQL foundation power node [Lao Du] class assignment
Cesium learning notes (V) custom geometry and appearance
Tidb v6.0.0 (DMR): initial test of cache table - tidb Book rush
我们如何拿到自己满意的薪资呢?这些套路还是需要掌握的
【NVMe2.0b 14-6】Format NVM、Keep Alive、Lockdown command
Markdown支持的emoji图标
【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command
[data analysis and display]
Dart tips
layer.open 当传值为数组或值太长时处理方法
Redis设计与实现(二)| 数据库(删除策略&过期淘汰策略)