我在數據庫連接內部有一個while循環,其中我想從數據庫檢索的值中創建一個對象。 這是我使用的代碼:每個循環創建一個新對象
public void dbConnect()
{
using (SqlConnection myConnection = new SqlConnection("server=CHAYU\\SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"database=restaurantApp; " +
"connection timeout=30"))
{
string oString = "Select * from Meal where availability=1";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
Meal m = new Meal();
m.mealID = Convert.ToInt32(oReader["mealId"]);
m.mealName = oReader["mealName"].ToString();
m.quantity=Convert.ToInt32(oReader["quantity"]);
m.timeToProduce = Convert.ToInt32(oReader["timeToProduce"]);
m.availability = true;
}
myConnection.Close();
}
}
}
我想每次加載窗體調用這個代碼,以便在開始創建對象,他們可以在以後進行操作。但是,我的問題是,如何通過在while循環內部具有不同的對象引用變量來執行此操作?
你的問題是不明確......但聽起來好像你應該創建一個集合... –
不要使用select * PLS,只選擇你所需要的。 – EaziLuizi
@Praveen絕對不是ArrayList! – dcastro