C#中的SQL嵌套查询和连接打开问题 [英] SQL Nested Queries in C# and Connection Open Problem

查看:112
本文介绍了C#中的SQL嵌套查询和连接打开问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个表,我的要求是使用每个表的父记录来获取它们的记录.

I have three tables and my requirement is to fetch their records by using the parent record of each table.

所以我有三个查询.这是一个代码示例:

So I have three queries. Here is a code sample:

首次查询

SQLConnection con = new SQLConnection("connectionstring");

SQLCommand cmd1 = new SQLCommand (1stQuery,con);
SQLDataReader rs1 = cmd1.DataReader();

while (rs1.Read()) {

// Making 2nd Query, 2nd Query is using 1st Query result

SQLCommand cmd2 = new SQLCommand(2ndQuery,con);
SQLDataReader rs2 = cmd2.DataReader();

while (rs2.Read()){

//Making 3rd Query using 2nd Query result
}
}

它给出一个错误,即已经有一个打开的DataReader.我不想关闭SQL连接并为每个查询打开它,因为这会降低性能.

It gives the error that there is already an open DataReader. I dont want to close the SQL connection and open it for each query, as this is bad for performance.

我只想对所有查询使用一个SQL连接.

I want to use only one SQL Connection for all the queries.

推荐答案

我建议使用 ExecuteDataSet .它将包含所有三个查询的结果.移动,这些查询应在存储过程中执行.

I suggest to use ExecuteDataSet. It will contain the result of all three queries. Moveover, These queries should be executed in stored procedure.

否则,您将邀请Sql Injections

Otherwise you are inviting Sql Injections

SQL注入

这篇关于C#中的SQL嵌套查询和连接打开问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆