当前位置:网站首页>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 .
边栏推荐
- 【kotlin 协程】万字协程 一篇完成kotlin 协程进阶
- [untitled]
- Gilbert Strang's course notes on linear algebra - Lesson 2
- Gilbert Strang's course notes on linear algebra - Lesson 4
- 【NVMe2.0b 14-5】Firmware Download/Commit command
- 1. Problems related to OpenGL window and environment configuration
- Cesium learning notes (V) custom geometry and appearance
- Common tools installation, configuration, compilation, link, etc
- 国债逆回购绝对安全吗 网上怎么开户
- 127.0.0.1、0.0.0.0和localhost
猜你喜欢

swagger使用

从0开始构建一个瀚高数据库Docker镜像

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

Summary of common pytoch APIs

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

Tidb 6.0: making Tso more efficient tidb Book rush

Axure make menu bar effect

Codeworks 5 questions per day (1700 for each) - the third day

Does the oscilloscope probe affect the measurement of capacitive load?

云服务器上部署仿牛客网项目
随机推荐
启动jar包报错UnsupportedClassVersionError,如何修复
Flink sql -- No factory implements ‘org.apache.flink.table.delegation.ExecutorFactory‘.
Wechat official account third-party platform development, zero foundation entry. I want to teach you
在浏览器输入url到页面展示出来
vim 从嫌弃到依赖(21)——跨文件搜索
PHP API to obtain QR code and combine to generate pictures
El input limit can only input numbers
Source code interpretation of detectron2 1--engine
codeforces每日5题(均1700)-第三天
Detectron2 source code reading 3-- encapsulating dataset with mapper
【NVMe2.0b 14-6】Format NVM、Keep Alive、Lockdown command
涂鸦Wi-Fi&BLE SoC开发幻彩灯带
【NVMe2.0b 14-1】Abort、Asynchronous Event Request、Capacity Management command
关于Lombok的@Data注解
【kotlin 协程】万字协程 一篇完成kotlin 协程进阶
Detectron2 source code reading 2--- using the configurable decorator to build the dataloader
Unity简单shader
Game 280 problem2: minimum operands to turn an array into an alternating array
示波器探头对测量电容负荷有影响吗?
[kotlin collaboration process] complete the advanced kotlin collaboration process