简体   繁体   English

使用SqlBulkCopy将CSV文件导入SQL Server

[英]Import a CSV file to SQL Server using SqlBulkCopy

I have this function that creates a table and then receives a CSV File. 我具有创建表然后接收CSV文件的功能。 I need an ID column in it that auto increments which would be used for later use. 我需要一个ID列,该列会自动递增,以供以后使用。 Therefore I ran the below query with the ID field. 因此,我使用ID字段运行以下查询。 Before it wasn't working because initially the CSV File had no ID column so when time came for it to be sent to the database there would be an error. 在它不起作用之前,因为最初CSV文件没有ID列,所以当将其发送到数据库时,会出现错误。 So my next idea was to add a blank ID column with no values to the CSV file and then attempt the query again. 因此,我的下一个想法是将没有值的空白ID列添加到CSV文件,然后再次尝试查询。 Still having an issue. 仍然有问题。 The error in my c# code is: "Received an invalid column length from the bcp client for colid 1." 我的C#代码中的错误是:“从bcp客户端收到针对colid 1的无效列长度。” Which am guessing is the ID column. 猜测是ID列。 Is there a way to have this ID column inserted and auto increment at the same time? 有没有一种方法可以同时插入此ID列并自动递增?

private void button2_Click(object sender, EventArgs e)
    {
        string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
        string query = "CREATE TABLE [dbo].[" + textBox1.Text + "](" +"ID int IDENTITY (1,1) PRIMARY KEY," + "[Code] [varchar] (13) NOT NULL," +
       "[Description] [varchar] (50) NOT NULL," + "[NDC] [varchar] (50) NULL," +
        "[Supplier Code] [varchar] (38) NULL," + "[UOM] [varchar] (8) NULL," + "[Size] [varchar] (8) NULL,)";


        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(query, connection);
            command.Connection.Open();
            command.ExecuteNonQuery();
        }

        SqlConnection con = new SqlConnection("Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True");
        string filepath = textBox2.Text; //"C:\\Users\\jdavis\\Desktop\\CRF_105402_New Port Maria Rx.csv";
        StreamReader sr = new StreamReader(filepath);
        string line = sr.ReadLine();
        string[] value = line.Split(',');
        DataTable dt = new DataTable();
        DataRow row;
        foreach (string dc in value)
        {
            dt.Columns.Add(new DataColumn(dc));
        }

        while (!sr.EndOfStream)
        {
            value = sr.ReadLine().Split(',');
            if (value.Length == dt.Columns.Count)
            {
                row = dt.NewRow();
                row.ItemArray = value;
                dt.Rows.Add(row);
            }
        }
        SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
        bc.DestinationTableName = textBox1.Text;
        bc.BatchSize = dt.Rows.Count;
        con.Open();
        bc.WriteToServer(dt);
        bc.Close();
        con.Close();

    }

I suppose you have a table in SQL Server which you created this way: 我想您在SQL Server中有一个表是通过以下方式创建的:

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 such code: 因此,要将值批量插入表中,可以使用以下代码:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM