C# 包含SQL连接的嵌入式循环
我有以下代码:C# 包含SQL连接的嵌入式循环,c#,.net,C#,.net,我有以下代码: SqlConnection connection1, connection2; SqlCommand command1, command2; SqlDataReader reader1, reader2; using (connection1 = new SqlConnection("connection string here")) { using (command1 = new SqlCommand(@"SELECT * FROM [SERVER1].[DATAB
SqlConnection connection1, connection2;
SqlCommand command1, command2;
SqlDataReader reader1, reader2;
using (connection1 = new SqlConnection("connection string here"))
{
using (command1 = new SqlCommand(@"SELECT * FROM [SERVER1].[DATABASE1].[TABLE1] WHERE COL1 = @COL1 AND COL2 = @COL2", connection1))
{
command1.Parameters.Add("@COL1", SqlDbType.VarChar, 255).Value = TextBox1.Text;
command1.Parameters.Add("@COL2", SqlDbType.VarChar, 255).Value = TextBox2.Text;
connection1.Open();
using (reader1 = command1.ExecuteReader())
{
while (reader1.Read())
{
int COL3Index = reader1.GetOrdinal("COL3");
Console.Write("### LOOP 1 ###");
Console.Write(reader1.GetDouble(COL3Index));
using (connection2 = new SqlConnection("same connection string here"))
{
using (command2 = new SqlCommand(@"SELECT * FROM [SERVER1].[DATABASE1].[TABLE2] WHERE COL1 = @COL1", connection1))
{
command2.Parameters.Add("@COL1", SqlDbType.Float).Value = reader1.GetDouble(COL3Index);
connection2.Open();
using (reader2 = command2.ExecuteReader())
{
while (reader2.Read())
{
int COL2Index = reader2.GetOrdinal("COL2");
Console.Write("### LOOP 2 ###");
Console.Write(reader2.GetDouble(COL2Index));
}
}
}
}
}
}
}
}
基本上每件事情中有2件,我需要做5次,即循环中循环中循环中循环中循环
第一个循环自身工作,但第二个循环不工作,并给出以下错误:
已存在与此命令关联的打开的DataReader,该命令
必须先关闭
在线:
using (reader2 = command2.ExecuteReader())
当我需要嵌入循环时,如何才能使其正常工作这是的定义,如果可能的话应该避免。我建议使用实体框架和子值之类的东西
如果无法避免,则循环遍历整个reader1结果,分配给本地集合,关闭reader1,然后迭代本地集合并基于本地值加载。如果启用了相同的数据库/连接字符串,则没有理由打开连接两次。这可以通过在连接字符串中添加
“MultipleActiveResultSets=True”
来实现
此外,您可以使用将数据加载到a/中,然后查询数据集。然而,这假设您的表不会太大,您可以将它们加载到内存中,否则ORM将是一个更好的选择
ORM解决方案,如LINQ to SQL或LINQ to Entities via Entity Framework(如Mike Cole的回答中所述),可以真正帮助您解决这个问题,因此您无需担心编写这些查询和处理连接。相反,您只需依赖DataContext来处理连接。检查创建
command2
的行。它绑定到connection1
(请参阅最后一个SqlCommand
构造函数参数)。哦,顺便说一句,我要重构这个方法……您的连接字符串允许多个打开的数据集吗?看一看这篇MSDN文章:。另外,在这里执行两个查询确实不需要两个连接。LINQtoSQL或LINQtoEntities可能需要研究(或任何其他ORM)。如果他使用所有列(否则他只需要在SELECT命令中缩小查询范围),这是一个完全有效的操作(通过DataReader循环)。在内存中加载列表是非常危险的。10张唱片?1000张唱片?一百万张唱片?也就是说,代码效率非常低(错误是他正在将command2创建到connection1中),但解决方案是使用连接。一个连接,一个查询。