Kamall
Kamall

Reputation: 13

Import .txt file to SQL database using VB.NET

I have a SQL database (local using vb.net) which has a table with 76 columns. The data that needs to be put into those columns is in the form of a plain delimited text file. I need to build a VB.NET application which will allow me to import the text file into the table in the database under their appropriate columns. Is there any way I can do this?

I'm very new to VB.NET. Can someone help me out with the code?

Thank You! Kamall

Upvotes: 0

Views: 4420

Answers (2)

marttronix
marttronix

Reputation: 9

If you have comma-separated values:

bulk insert tableName
from 'C:\myfile.txt'
with (fieldterminator = ',', rowterminator = '\n')
go

For tab-separated values use:

bulk insert tableName
from 'C:\myfile.txt'
with (fieldterminator = ',', rowterminator = '\n')
go

Upvotes: 1

Stefan Steiger
Stefan Steiger

Reputation: 82406

76 columns ?
Must be the god-table antipattern ...

   Public Sub CopyToDataBase(dt As DataTable)

    Using Conn As SqlConnection = New SqlConnection("YOUR_CONNECTION_STRING")
        Conn.Open()

        Using s As SqlBulkCopy = New SqlBulkCopy(Conn)

            s.DestinationTableName = "TableName"
            s.WriteToServer(dt)
            s.Close()

        End Using

        Conn.Close()
    End Using
End Sub

of course this requires the table to have a primary key.

Upvotes: 0

Related Questions