从SQL读卡器到数据表的数据-读卡器关闭时调用Read的尝试无效



我一直在尝试,但仍然不知道如何解决这个问题,不断出现同样的错误。我想从数据库中获取数据到txt文件。

    using (conn)
{
    conn.Open();
    SqlCommand cmd = new SqlCommand(command)
    cmd.Connection = (SqlConnection)conn;
    using (cmd)
    {
        SqlDataReader reader = cmd.ExecuteReader();
        using(reader)
        {
             while (reader.Read())
             {
                  dt.Load(reader);
             }
        }
        using (StreamWriter sw = new StreamWriter(txtPath.Text + fileName))
        {
            // write to text file from Datatable dt
        }  }

尝试插入代码,如下所示:

 DataTable myDataTable = new DataTable();

        using (SqlConnection myConnection = new SqlConnection(yourDBconn)
        {
                yourDBconn.Open();
                using (SqlDataAdapter myAdapter = new SqlDataAdapter(strYourQuery, yourDBconn))
                {
                    myAdapter.Fill(myDataTable);
                }
            }
        }

给你。经过测试。

var customers = new List<Tuple<int, string>>(); // the list of ID, Name
using (var con = new SqlConnection("your connection string"))
{
    using(SqlCommand cmd = new SqlCommand("select ID, Name from Customer", con))
    {
        con.Open();       
        using(SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                customers.Add(new Tuple<int, string>(
                    (int)reader["ID"], reader["Name"].ToString()));
            }
        }
    }
}
// Store customers to file

相关内容

  • 没有找到相关文章

最新更新