ADO.NET 学习笔记(九) 练习:数据的导出

private void btnExport_Click(object sender, EventArgs e)

{

  string filePath = @"F:\WXX\测试文件夹1\导出数据测试\省市.txt";

  if (!File.Exists(filePath))

  {

    using (FileStream fs = File.Create(filePath)) { }

  }



  using (FileStream fileStream = File.OpenWrite(filePath))

  {

    using (StreamWriter streamWriter = new StreamWriter(fileStream))

    {

      using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))

      {

        conn.Open();

        using (SqlCommand cmd = conn.CreateCommand())

        {

          cmd.CommandText = "select * from T_Province";

          using (SqlDataReader reader = cmd.ExecuteReader())

          {

            while (reader.Read())

            {

              streamWriter.WriteLine(reader.GetString(reader.GetOrdinal("FProvince")) + "|" + reader.GetString(reader.GetOrdinal("FCity")));

            }

          }

        }

      }

    }

  }

  MessageBox.Show("导出完成");

}

 

你可能感兴趣的:(.net)