[英]Using multiple result sets from a SQLDataReader
我目前正在研究一個學校項目,希望有人可以指出以下內容的在線教程。 這是一項家庭作業,所以我不是在找別人給我答案,而是想找到與我所打算的解決方案相似的教程。 我一直在使用SQLDataReader和Linq進行搜索,但找不到與我追求的解決方案類似的解決方案。
我正在將C#客戶端項目連接到SQL數據庫。 該數據庫包含一個用於狗的表和一個用於BreedOfDog的表,以說明狗可能屬於混合犬種這一事實。 BreedOfDog具有兩個值DogId和BreedId,它們將Dog表連接到Breed表。 在我的客戶端應用程序上,有一個容器,用於顯示狗的信息。 還有一個Dog類,其中包含品種對象列表。 品種對象列表將用於用狗的品種填充列表框。 這是我打算用偽代碼執行的操作:
創建一個允許多個結果集的SQL查詢。 我將使用SQL數據庫中的存儲過程
打開與SQL數據庫的連接
執行第一個查詢,將獲得Dog對象的列表
執行第二個查詢。 此查詢將在第一個查詢中拉出每條狗的DogId,在BreedOfDog上執行查詢,創建Breed對象的列表並將其添加到Dog對象。 將對“狗”列表中的每個狗執行此操作。
緊密連接
您可以指出我的觀點嗎?
List<DogClass> Dogs = new List<DogClass>();
string SQL = "select DogId from Dog";
SqlCommand Command = new SqlCommand(SQL, Con);
SqlDataReader Reader = Command.ExecuteReader();
while (Reader.Read())
{
DogClass Dog = new DogClass(Reader, Con);
Dogs.Add(Dog);
}
Reader.Close();
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
class DogClass
{
string DogId;
List<BreedClass> Breeds = new List<BreedClass>();
internal DogClass(SqlDataReader Reader, SqlConnection Con)
{
DogId = Convert.ToString(Reader.GetValue(Reader.GetOrdinal("DogId"))).Trim();
string SQL = "select BreedOfDog from Breeds where DogID = '" + DogId + "'";
SqlCommand Command = new SqlCommand(SQL, Con);
SqlDataReader Reader2 = Command.ExecuteReader();
while (Reader2.Read())
{
BreedClass Breed = new BreedClass(Reader);
Breeds.Add(Breed);
}
Reader2.Close();
}
}
using System;
using System.Data.SqlClient;
class BreedClass
{
internal string Breed;
internal BreedClass(SqlDataReader Reader)
{
Breed = Convert.ToString(Reader.GetValue(Reader.GetOrdinal("BreedOfDog"))).Trim();
}
}
我記得在程序員學校(學院)也遇到過同樣的問題! 您會喜歡linq to sql的。 您需要做的是:
DataClasses1DataContext db = new DataClasses1DataContext();
。 IQueryable<BREED> breeds = db.BREEDs.Take(50);
一樣簡單IQueryable<BREED> breeds = db.BREEDs.Take(50);
。 有關如何使用LINQ讀取/寫入/刪除/等的信息,請參閱本文。 http://msdn.microsoft.com/en-us/library/bb882643.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.