SqlBulkCopy从记事本批量复制数据4

来源:互联网 发布:欧洲卡车模拟mac版 编辑:程序博客网 时间:2024/05/22 19:26
privatestatic DataTable GetTableSchema()
    {
        DataTable dataTable =new DataTable();
 
        dataTable.Columns.Add("username", Type.GetType("System.String"));
 
        dataTable.Columns.Add("password", Type.GetType("System.String"));
 
        dataTable.Columns.Add("account", Type.GetType("System.String"));
 
        returndataTable;
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
static void Main(string[] args)
        {
            try
            {
  
                stringfilepath = @"TXT文件地址";
                StreamReader file =new StreamReader(filepath, System.Text.Encoding.Default);
  
                stringusername;
                stringpassword;
                stringacout;
  
                Stopwatch stopwatch =new Stopwatch();
                stopwatch.Start();
                DataTable dataTable = GetTableSchema();
                while(true)
                {
                //从TXT读取数据部分
                DataRow dataRow = dataTable.NewRow();
                dataRow["username"] = username;
                dataRow["password"] = password;
                dataRow["account"] = acout;
                dataTable.Rows.Add(dataRow);
  
                }
  
                stringconnectionString = "MSSQL连接字符串";
                SqlBulkCopy sqlBulkCopy =new SqlBulkCopy(connectionString);
                sqlBulkCopy.DestinationTableName ="表名";
                sqlBulkCopy.BatchSize = dataTable.Rows.Count;
                SqlConnection sqlConnection =new SqlConnection(connectionString);
                sqlConnection.Open();
  
                if(dataTable != null&& dataTable.Rows.Count != 0)
                {
                    sqlBulkCopy.WriteToServer(dataTable);
                }
                sqlBulkCopy.Close();
                sqlConnection.Close();
                dataTable.Clear();
                stopwatch.Stop();
  
                file.Close();
                }
            catch(IOException e)
            {
                Console.WriteLine(e.ToString());
            }
  
        }
原创粉丝点击