简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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