SQL Server 数据导入

时间:2022-06-01 20:49:37

ExcuteNonQuery() 返回影响的行数

ExcuteSacalar() 返回第一行的第一列

ExcuteReader() Reader指针,指向表的表头

 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 UserInfo
15 {
16     public partial class MainFrm : Form
17     {
18         public MainFrm()
19         {
20             InitializeComponent();
21         }
22 
23         private void btnOpen_Click(object sender, EventArgs e)
24         {
25             using (OpenFileDialog ofd = new OpenFileDialog())
26             {
27                 ofd.Filter = "文本文件|*.txt";
28                 if (ofd.ShowDialog()==DialogResult.OK)
29                 {
30                     this.textPath.Text = ofd.FileName;
31                     //导入数据
32                     ImportData(ofd.FileName);
33                 }
34             }
35 
36         }
37 
38         //导入数据的方法
39         private void ImportData(string fileName)
40         {
41             string temp = string.Empty;
42             using (StreamReader reader=new StreamReader(fileName,Encoding.UTF8))
43             {
44                 //去掉第一行
45                 reader.ReadLine();
46                 //string str = "server=.;uid=sa;pwd=tracy05;database=Test";
47                 string str = ConfigurationManager.ConnectionStrings["sqlConn"].ConnectionString;
48                 using (SqlConnection conn=new SqlConnection(str))
49                 {
50                     using (SqlCommand cmd=conn.CreateCommand())
51                     {
52                         conn.Open();
53                         while (!string.IsNullOrEmpty(temp = reader.ReadLine()))
54                         {
55                             var strs = temp.Split(',');
56                             string sql = string.Format(@"INSERT INTO 
57                                                 UserInfo(StuName,StuSex,StuBirthdate,StuPhone) 
58                                                 VALUES('{0}','{1}','{2}','{3}')",
59                                                         strs[1], strs[2], strs[3], strs[4]);
60                             cmd.CommandText = sql;
61                             cmd.ExecuteNonQuery();
62                         }
63                     }
64 
65                 }
66 
67             }
68         }
69     }
70 }