1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Data.SqlClient; 6 using System.IO; 7 8 namespace 数据库导出数据 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 string str = "Data Source =.; Initial Catalog = mysql; Integrated Security = True;"; 15 string sql = "select * from users"; 16 17 //Data Source=.;Initial Catalog=mysql;Integrated Security=True 18 //下面有4个using,streamwriter必须使用using!! 19 using (SqlConnection con = new SqlConnection(str)) 20 { 21 using (SqlCommand cmd = new SqlCommand(sql, con)) 22 { 23 con.Open(); 24 using (SqlDataReader reader = cmd.ExecuteReader()) 25 { 26 if (reader.HasRows) 27 { 28 using (StreamWriter sw = new StreamWriter("1.txt")) 29 { 30 sw.WriteLine("{0},{1},{2}", reader.GetName(0), reader.GetName(1), reader.GetName(2)); 31 while (reader.Read()) 32 { 33 sw.WriteLine("{0},{1},{2}", reader[0], reader[1], reader[2]); 34 } 35 } 36 } 37 } 38 } 39 } 40 Console.WriteLine("导出成功!"); 41 Console.ReadKey(); 42 } 43 } 44 }