當嘗試從SQL查詢中將結果提取到C#中的對象列表中時遇到了問題。出於某種原因,它會覆蓋最近查詢結果的所有行,我看不到我做錯了什麼。用於測試的Console.WriteLine返回正確的數據,以便查詢正常運行。將SQL結果添加到對象列表時,所有記錄都被最近的結果覆蓋
我的代碼是:
private void getData(string qry)
{
int count = 0;
string strProject = "ARTUR-PC\\SQLEXPRESS"; //Enter your SQL server instance name
string strDatabase = "Northwind"; //Enter your database name
string strUserID = "Artlemaks"; // Enter your SQL Server User Name
string strPassword = "rootUser"; // Enter your SQL Server Password
string strconn = "data source=" + strProject +
";Persist Security Info=false;database=" + strDatabase +
";user id=" + strUserID + ";password=" +
strPassword + ";Connection Timeout = 0";
//conn = new SqlConnection(strconn);
using (SqlConnection connection = new SqlConnection(strconn))
{
List<CustomerObj> Customers = new List<CustomerObj>();
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = qry;
cmd.ExecuteNonQuery();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
row.custID = reader[0] as int?;
row.cmpName = reader[1] as string;
row.cntName = reader[2] as string;
row.cntTitle = reader[4] as string;
row.address = reader[5] as string;
row.city = reader[3] as string;
row.region = reader[6] as string;
row.postalCode = reader[7] as string;
row.country = reader[8] as string;
row.phone = reader[9] as string;
row.fax = reader[10] as string;
Console.WriteLine("{0}\t{1}", reader[0], reader[1]);
Customers.Add(row);
}
}
reader.Close();
connection.Close();
}
我抽了一口煙,得出了同樣的結論......完美地工作,謝謝你確認我的想法! – ArtleMaks