Import a CSV file to SQL Server using SqlBulkCopy

前端 未结 1 1046
臣服心动
臣服心动 2020-12-18 16:04

I have this function that creates a table and then receives a CSV File. I need an ID column in it that auto increments which would be used for later use. Therefore I ran the

相关标签:
1条回答
  • 2020-12-18 16:55

    I suppose you have a table in SQL Server which you created this way:

    CREATE TABLE [dbo].[Table1] (
        [Column1]   INT           IDENTITY (1, 1) NOT NULL,
        [Column2]   NVARCHAR (50) NOT NULL
    );
    

    file containing such values:

    Column1,Column2
    1,N1
    2,N2
    3,N3
    

    So to bulk insert values to the table you can use SqlBulkCopy this way:

    var lines = System.IO.File.ReadAllLines(@"d:\data.txt");
    if (lines.Count() == 0) return;
    var columns = lines[0].Split(',');
    var table = new DataTable();
    foreach (var c in columns)
        table.Columns.Add(c);
    
    for (int i = 1; i < lines.Count() - 1; i++)
        table.Rows.Add(lines[i].Split(','));
    
    var connection = @"your connection string";
    var sqlBulk = new SqlBulkCopy(connection);
    sqlBulk.DestinationTableName = "Table1";
    sqlBulk.WriteToServer(table);
    
    0 讨论(0)
提交回复
热议问题