当前位置: 代码迷 >> SQL >> SqlBulkCopy从记事簿批量复制数据4
  详细解决方案

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

热度:114   发布时间:2016-05-05 15:24:34.0
SqlBulkCopy从记事本批量复制数据4
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());
            }
  
        }