数据库数据导出和导入
思路:
--思路:
1、找到文件
2、读取文件
3、第一行 忽略
4、insert
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Configuration; 5 using System.Data; 6 using System.Data.SqlClient; 7 using System.Drawing; 8 using System.IO; 9 using System.Linq; 10 using System.Text; 11 using System.Threading.Tasks; 12 using System.Windows.Forms; 13 14 namespace _04DataInport 15 { 16 public partial class MainFrm : Form 17 { 18 public MainFrm() 19 { 20 InitializeComponent(); 21 } 22 23 private void btnSelectDataFile_Click(object sender, EventArgs e) 24 { 25 using (OpenFileDialog ofd = new OpenFileDialog()) 26 { 27 ofd.Filter = "文本文件|*.txt"; //winform文件知识需要强化学习 28 if (ofd.ShowDialog() == DialogResult.OK) 29 { 30 this.txtFilePath.Text = ofd.FileName; 31 32 //导入数据 33 ImportData(ofd.FileName); 34 MessageBox.Show("插入成功!!!"); 35 } 36 } 37 } 38 private void ImportData(string fileName) 39 { 40 string temp = string.Empty; 41 //第一步:拿到文件 42 //File.ReadAllLines(); 43 using (StreamReader reader=new StreamReader(fileName,Encoding.UTF8)) //读取文件的知识 44 { 45 reader.ReadLine(); //去掉第一行,winform知识,加强 46 // string connStr = "server=115.29.151.176;uid=sa;pwd=123456;database=LJK_SQLServerDB"; 47 //添加“ConfigurationManager”引用,配置文件的使用 48 string connStr =ConfigurationManager.ConnectionStrings["_04DataInport.Properties.Settings.LJK_SQLServerDBConnectionString"].ConnectionString; 49 50 using (SqlConnection conn=new SqlConnection(connStr)) 51 { 52 using (SqlCommand cmd=conn.CreateCommand()) 53 { 54 conn.Open(); //链接只能打开一次 55 while (!string.IsNullOrEmpty(temp = reader.ReadLine())) //判断读取的行不为空,reader.ReadLine()为逐行读取 56 { 57 //Console.WriteLine(temp); 58 //把字符串进行分割,然后生成一条sql插入到数据库中 59 string[] strings = temp.Split(','); 60 string sql = string.Format(@" 61 insert into User_Info 62 (User_Name) 63 values('{0}')", strings[1]); // 唯一键、重复键、主键等 64 cmd.CommandText = sql; 65 cmd.ExecuteNonQuery(); 66 }//end while 67 }//end using cmd 68 }//end using conn 69 }//end reader 70 } 71 } 72 }