设计界面:
向该form中拖入一个openfiledialog,重命名为:opfdImport
txt文件中的内容为:
实现代码为:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.IO; 10 using System.Data.SqlClient; 11 using System.Data.Sql; 12 using System.Configuration; 13 14 namespace 数据的导入导出 15 { 16 public partial class Form1 : Form 17 { 18 public Form1() 19 { 20 InitializeComponent(); 21 } 22 23 private void Form1_Load(object sender, EventArgs e) 24 { 25 26 } 27 28 private void btnimport_Click(object sender, EventArgs e) 29 { 30 if (opfdImport .ShowDialog ()!=DialogResult .OK) 31 { 32 return ; 33 } 34 // string strmapth = @"Data Source=.SQLEXPRESS;AttachDbFilename=F:学习C#练习C#时的代码ado.net数据的导入导出Users.mdf;Integrated Security=True;User Instance=True"; 35 string strmapth = ConfigurationManager.ConnectionStrings["mydb"].ConnectionString; 36 using (SqlConnection conn = new SqlConnection(strmapth)) 37 { 38 conn.Open(); 39 string InsertYuju = "Insert into T_Persons (Name,age) values (@dbname,@dbage)"; 40 using (SqlCommand cmd = new SqlCommand(InsertYuju, conn)) 41 { 42 using (FileStream fileStream = File.OpenRead(opfdImport.FileName)) 43 { 44 using (StreamReader streamReader = new StreamReader(fileStream)) 45 { 46 string line = null; 47 while ((line = streamReader.ReadLine()) != null) 48 { 49 string[] strs = line.Split('|'); 50 string name = strs[0]; 51 int age = Convert.ToInt32(strs[1]); 52 cmd.Parameters.Clear(); 53 cmd.Parameters.Add(new SqlParameter("dbname", name)); 54 cmd.Parameters.Add(new SqlParameter ("dbage",age)); 55 cmd.ExecuteNonQuery(); 56 57 } 58 } 59 } 60 } 61 MessageBox.Show("导入成功!"); 62 } 63 } 64 } 65 }
运行结果为:
至此工作结束。