punjabtechnicaluniversity.blogspot.in
Microsoft provides System.Data.OleDb namespace to communicate with databases like Access , oracle etc.In short any OLE DB-Compliant database can be connected using System.Data.OldDb namespace.
Private Sub loadData()
Dim strPath As String
strPath = AppDomain.CurrentDomain.BaseDirectory
Dim objOLEDBCon As New
OleDbConnection(“Provider=Microsoft.Jet.OLEDB.4.0;Data Source =” &
strPath & “Nwind.mdb”)
Dim objOLEDBCommand As OleDbCommand
Dim objOLEDBReader As OleDbDataReader
Try
objOLEDBCommand = New OleDbCommand(“Select FirstName
from Employees”)
objOLEDBCon.Open()
objOLEDBCommand.Connection = objOLEDBCon
objOLEDBReader = objOLEDBCommand.ExecuteReader()
Do While objOLEDBReader.Read()
lstNorthwinds.Items.Add(objOLEDBReader.GetString(0))
Loop
Catch ex As Exception
Throw ex
Finally
objOLEDBCon.Close()
End Try
End Sub
The main heart is the “Loaddata()” method which actually loads the data in listbox.
Microsoft provides System.Data.OleDb namespace to communicate with databases like Access , oracle etc.In short any OLE DB-Compliant database can be connected using System.Data.OldDb namespace.
Private Sub loadData()
Dim strPath As String
strPath = AppDomain.CurrentDomain.BaseDirectory
Dim objOLEDBCon As New
OleDbConnection(“Provider=Microsoft.Jet.OLEDB.4.0;Data Source =” &
strPath & “Nwind.mdb”)
Dim objOLEDBCommand As OleDbCommand
Dim objOLEDBReader As OleDbDataReader
Try
objOLEDBCommand = New OleDbCommand(“Select FirstName
from Employees”)
objOLEDBCon.Open()
objOLEDBCommand.Connection = objOLEDBCon
objOLEDBReader = objOLEDBCommand.ExecuteReader()
Do While objOLEDBReader.Read()
lstNorthwinds.Items.Add(objOLEDBReader.GetString(0))
Loop
Catch ex As Exception
Throw ex
Finally
objOLEDBCon.Close()
End Try
End Sub
The main heart is the “Loaddata()” method which actually loads the data in listbox.
Note:- This source code has the connection string hard coded in the program itself which is not a good programming practice.For windows application the best place to store connectionstring is “App.config”.Also note “AppDomain.CurrentDomain.BaseDirectory” function this gives the current path of the running exe which is “BIN” and the MDB file is in that directory.Also note the finally block which executes irrespective that there is error or not.Thus ensuring that all the connection to the datastore is freed.It’s best practice to put all clean up statements in finally block thus ensuring that the resources are deallocated properly.
0 comments:
Post a Comment
North India Campus