有一段文本
1 2008/12/29 1000 Bush
2 2008/11/23 1600 Carter
3 2008/10/05 700 Bush
4 2008/09/28 300 Bush
5 2008/08/06 2000 Adams
6 2008/07/21 100 Carter
导入数据库
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 ConsoleApplication2 9 { 10 class Program 11 { 12 static void Main(string[] args) 13 { 14 int counter = 0; 15 string line; 16 StreamReader fs; 17 fs = new StreamReader(@"F:\SQL\插入数据库的文本.txt"); 18 19 while ((line = fs.ReadLine()) != null) 20 { 21 string delim = " "; 22 char[] delimiter = delim.ToCharArray(); 23 string[] split = null; 24 25 for (int i = 1; i <= line.Length; i++) 26 { 27 split = line.Split(delimiter, i); 28 } 29 30 string id = split[0]; 31 int O_id = int.Parse(id); 32 string orderDate = split[1]; 33 string orderPrice = split[2]; 34 string customer = split[3]; 35 36 AddDB(O_id, orderDate, orderPrice, customer); 37 counter++; 38 } 39 fs.Close(); 40 41 Console.WriteLine("插入成功共计插入 {0} 条数据",counter++); 42 } 43 44 public static int AddDB(int O_id, string orderDate, string orderPrice, string customer) 45 { 46 47 int num = 0; 48 string connString = @"Data Source=PC-201003301650\SQLEXPRESS;Initial Catalog=LOGINDB.MDF;Integrated Security=True"; 49 50 SqlConnection conn = new SqlConnection(connString); 51 52 string sql = "insert into Orders values(" + O_id + ",'" + orderDate + "','" + orderPrice + "','" + customer + "')"; 53 54 try 55 { 56 conn.Open(); 57 SqlCommand cmd = new SqlCommand(sql, conn); 58 num = int.Parse(cmd.ExecuteNonQuery().ToString()); 59 } 60 catch (SqlException e) 61 { 62 throw e; 63 } 64 finally 65 { 66 conn.Colse(); 67 } 68 return num; 69 } 70 } 71 }