【问题标题】:SQL get to C# with SqlDataReaderSQL 使用 SqlDataReader 访问 C#
【发布时间】:2018-04-21 07:59:49
【问题描述】:

我有问题。我想从我的 SQL Server 数据库中获取数据。当代码运行时,第一行没有被添加到我的数组列表中。所有其他行都成功添加。在 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 循环。只需将其删除,它应该可以正常工作
  • 我会删除查询中的 ExecuteNonQuery()。

标签: c# sql sql-server connection sqldatareader


【解决方案1】:

您正在尝试以两种不同的方式迭代阅读器 - 使用 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>在这种情况下。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多