Bulk Insert CSV File into SQL Server Table using C# VB.Net

In many cases we need to insert CSV file into SQL Server Database table. Here in this article I will explain how one can “Insert CSV File Data into Sql Server Table using Bulk Insert“. But you can use Bulk Insert only if your DataBase server and Application server is same. Otherwise not.

Output:
Bulk Insert CSV file into SQl Server

The CSV file to Insert:

1, Bulk Insert CSV File into SQL Server Table using C# VB.Net
2, INSERT CSV FILE DATA into SQL Server Table using BULK INSERT
3, Insert CSV file into DataBase using Bulk Insert

To insert the CSV file Create a Table First:

CREATE TABLE [dbo].[Articles](
	[ID] [int] NULL,
	[Title] [varchar](max) NULL
) ON [PRIMARY]

Import the below Namespace:
1. System.Data.SqlClient

Bulk Insert CSV File into SQL Server Table using C#

        private void Form1_Load(object sender, EventArgs e)
        {
            using (SqlConnection Conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;"))
            {
                string sql = "BULK INSERT dbo.Articles FROM 'C:\\Articles.csv' WITH (FIELDTERMINATOR = ',')";
                SqlCommand SqlCmd = new SqlCommand();
                SqlCmd.CommandTimeout = 0;
                Conn.Open();
                SqlCmd.Connection = Conn;
                SqlCmd.CommandText = sql;
                int nInserted=SqlCmd.ExecuteNonQuery();
                MessageBox.Show(string.Format("Total {0} Rows Inserted!", nInserted));
            }
        }

Bulk Insert CSV File into SQL Server Table using VB.Net

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Using Conn As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;")
            Dim sql As String = "BULK INSERT dbo.Articles FROM 'C:\Articles.csv' WITH (FIELDTERMINATOR = ',')"
            Dim SqlCmd As New SqlCommand()
            SqlCmd.CommandTimeout = 0
            Conn.Open()
            SqlCmd.Connection = Conn
            SqlCmd.CommandText = sql
            Dim nInserted As Integer = SqlCmd.ExecuteNonQuery()
            MessageBox.Show(String.Format("Total {0} Rows Inserted!", nInserted))
        End Using

    End Sub

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code