I need to import records from a comma delimited CSV file into an existing table in SQL Server R2 database using Visual Basic .Net 2010. Existing records in the table are to be deleted prior to import. I have been able to create an in-memory temporary DataTable and populate the records from CSV file using TextFieldParser. I have checked it by binding the in-memory DataTable to a DataGridView. But I am clueless in the second part i.e. how to insert records into the SQL table from the in-memory DataTable.
I have done the following:
Can anybody please help/guide me??Code:Dim TextFileReader As New TextFieldParser("C:\csvtosql\StockVB\VFPFiles\ExpSysusers.csv") TextFileReader.TextFieldType = FileIO.FieldType.Delimited TextFileReader.SetDelimiters(",") Dim TextFileTable As DataTable = Nothing Dim Column As DataColumn Dim Row As DataRow Dim UpperBound As Int32 Dim ColumnCount As Int32 Dim CurrentRow As String() Dim intCount As Integer intCount = 0 CurrentRow = TextFileReader.ReadFields() ' Ignore the header While Not TextFileReader.EndOfData Try CurrentRow = TextFileReader.ReadFields() If Not CurrentRow Is Nothing Then ''# Check if DataTable has been created If TextFileTable Is Nothing Then TextFileTable = New DataTable("TextFileTable") ''# Get number of columns UpperBound = CurrentRow.GetUpperBound(0) ''# Create new DataTable For ColumnCount = 0 To UpperBound Column = New DataColumn() Column.DataType = System.Type.GetType("System.String") Column.ColumnName = "Column" & ColumnCount Column.Caption = "Column" & ColumnCount Column.ReadOnly = True Column.Unique = False TextFileTable.Columns.Add(Column) Next End If intCount = intCount + 1 Row = TextFileTable.NewRow For ColumnCount = 0 To UpperBound Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString Next TextFileTable.Rows.Add(Row) End If Catch ex As Exception MsgBox("Line " & ex.Message & "is not valid and will be skipped.") End Try End While TextFileReader.Dispose() DataGridView1.DataSource = TextFileTable MsgBox(intCount & " Records Read.")




Reply With Quote
