[英]SQL get to C# with SqlDataReader
我有個問題。 我想從我的SQL Server數據庫中獲取數據。 代碼運行時,第一行沒有添加到我的arraylist中。 所有其他行均已成功添加。 在SQL Server中,查詢工作正常,但在VS中,查詢無效。
private void button1_Click(object sender, EventArgs e)
{
SqlConnection baglanti = new SqlConnection("server=.; Initial Catalog=TripData;Integrated Security=SSPI");
baglanti.Open();
SqlCommand komut = new SqlCommand();
komut.CommandText = "select top 50 trip_ID from Sayfa1$";
komut.Connection = baglanti;
komut.ExecuteNonQuery();
SqlDataReader oku = komut.ExecuteReader();
while (oku.Read())
{
foreach (var item in oku)
{
gecici.Add(oku["trip_ID"].ToString());
}
}
}
您試圖以兩種不同的方式遍歷讀取器-同時使用foreach
循環和使用while (reader.Read())
。 您應該做一個或另一個-我個人使用while (reader.Read())
看到的代碼比foreach
方法更多。
另外,我建議對代碼中的一次性對象使用using
語句-不要先調用ExecuteNonQuery
。 (目前尚不清楚為什么要這么做)。 所以你可以這樣寫:
// Note that this looks like a mixture of UI and non-UI code; consider separating
// them for greater code reuse, separation of concerns etc.
private void button1_Click(object sender, EventArgs e)
{
// Declare connectionString elsewhere, or have a common method to open the connection.
// You're likely to need that in multiple places.
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand("select top 50 trip_ID from Sayfa1$", connection))
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
gecici.Add(oku["trip_ID"].ToString());
}
}
}
}
}
(此外,如果您確實按照帖子的建議使用ArrayList
,那么我強烈建議您開始使用通用集合,例如,在這種情況下使用List<string>
。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.