Jump to content


Check out our Community Blogs

poojab

Member Since 23 Jul 2012
Offline Last Active Aug 14 2012 02:08 AM
-----

Posts I've Made

In Topic: [SOLVED] Add Value From Text File To Database Using Vb.net And Ms Sql

24 July 2012 - 12:34 AM

I got the code working....

Find below

'open database connection
Open_DB_Connection()
Dim i As Integer = 1
Dim dir As DirectoryInfo = New DirectoryInfo(Application.StartupPath & "\Images\")

'get the number of folders in the main folder
Dim number As Integer
number = System.IO.Directory.GetDirectories(dir.ToString).Length
Debug.Print("number: " + number.ToString)
Dim myCommand As SqlCommand

'delete the data if any present in database
Try
Dim myCommandD As SqlCommand
myCommandD = New SqlCommand("DELETE FROM Test.dbo.Test3project", Connection)
myCommandD.ExecuteNonQuery()

'check if main folder is empty
If number = 0 Then
MsgBox("No files found")
Else
'get the array of directories
Dim mainfolder As DirectoryInfo() = dir.GetDirectories()
Dim foldername As DirectoryInfo

For Each foldername In mainfolder
Debug.Print("folder name: " + foldername.ToString)
Dim sr As StreamReader = New StreamReader(Application.StartupPath + "\Images\" + foldername.ToString + "\patientreg.txt")
'read the content of the file
Dim line As String = sr.ReadLine()

'split the file according to the separator
Dim fields() As String = line.Split("*")

'insert the data into database
myCommand = New SqlCommand("INSERT INTO Test.dbo.Test3project VALUES('" & fields(0) & "','" & fields(1) & "', '" & fields(2) & "', '" & fields(3) & "', '" & fields(4) & "','" & fields(5) & "','" & fields(6) & "')", Connection)
Debug.Print("Query: " + myCommand.CommandText)
myCommand.ExecuteNonQuery()

Next
MsgBox("Saved...showing data to datagrid")

'showing database data to datagrid
Try
Dim myCommand1 As New SqlCommand
With myCommand1
.CommandText = "select * from Test.dbo.Test3project"
.CommandType = CommandType.Text
.Connection = Connection
End With
Dim dt As New DataTable
dt.Load(myCommand1.ExecuteReader)
With DataGridView1
.AutoGenerateColumns = True
.DataSource = dt
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Close_DB_Connection()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download