You are on page 1of 14

Database Connection

Objective
In this chapter, you will learn about : To make connection to Microsoft Access database using Visual Basic 2008. To Read (Select) and write (Insert, Update & Delete) data from/to table in the database. Students Note

7.0 Introduction
Before we start doing this session, download/copy AddressBook.mdb database and save it into D: directory. The AddressBook.mdb has only one table: tblContacts, which the detail as follows: Field Name ID FirstName Surname Data Type Number Text Text Field Size Long Integer 20 20

We will access the database and read or write the data from/to its table. The type of access can be: 1. Read data . 2. Insert/add new data 3. Search data 4. Update data 5. Delete data

7.1 Create Interface


Create a new project and name it as Lab07. On your new form, drag some control and rearrange it like Figure 7.1(a) and then do some modification as show in Table 7.1 so that it will be like Figure 2.1(b).

Students Note

7.1 (a)

7.1(b)

Table 7.1: Changing Control and Properties Control


Form1

Properties
Text Name Text Text Text Name Name Name Text Name Text Name Text Name Text Name Text Name Text Name Enabled Text Name Enabled Text Name Text Name Text Name Text Name AddressBook frmAddressBook ID FirstName Surname txtID txtFirstName txtSurname << btnFirst < btnPrevious > btnNext >> btnLast Add/Insert btnAdd Commit btnCommit False Cancel btnCancel False Search btnSearch Update btnUpdate Delete btnDelete Close btnClose

Value

Students Note

Label1 Label2 Label2 TextBox1 TextBox2 TextBox3 Button1

Button2

Button3

Button4

Button5

Button6

Button7

Button8

Button9

Button10

Button9

7.2 Create Connection to Database


We have to make connection to database first before reading/writing data. The connection is constructed with the following code:
Public Class frmAddressBook 'Variables Declaration: Dim con As New OleDb.OleDbConnection Dim con As New OleDb.OleDbConnection '***********Parameters to connect to database Dim dbProvider As String Dim dbSource As String '********Parameters to connect data adapter and data set ***** Dim ds As New DataSet Dim da As OleDb.OleDbDataAdapter Dim sql As String '*********Parameters needed to manipulate the tblContacts********* Dim MaxRows As Integer Dim baris As Integer Add code here: Private Sub frmAddressBook_Load Private Sub DisplayRecord() Private Sub ClearAllTextBox() Private Sub btnFirst_Click Private Sub btnPrevious_Click Private Sub btnNext_Click Private Sub btnLast_Click Private Sub btnAdd_Click Private Sub btnCommit_Click Private Sub btnCancel_Click Private Sub btnSearch_Click Private Sub btnUpdate_Click Private Sub btnDelete_Click Private Sub btnClose_Click End Class

Students Note

Private Sub frmAddressBook_Load code:


Private Sub frmAddressBook_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 'connect to database dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" dbSource = "Data Source = D:\AddressBook.mdb" con.ConnectionString = dbProvider & dbSource 'connect to data / to read data from the table con.Open() sql = "Select * FROM tblContacts" da = New OleDb.OleDbDataAdapter(sql, con) da.Fill(ds, "Contacts") con.Close() 'Kira jumlah record atau baris dalam table MaxRows = ds.Tables("Contacts").Rows.Count 'If the table is not empty then display the first record If MaxRows > 0 Then baris = 0 DisplayRecord() End If End Sub

Students Note

7.3 Code to display and clear the data in the TextBox


Following the code needed to display the data to your TextBox:
'Display Record Private Sub DisplayRecord() If baris < MaxRows Then txtID.Text = ds.Tables("Contacts").Rows(baris).Item("ID") txtFirstName.Text = ds.Tables("Contacts").Rows(baris).Item("FirstName") txtSurname.Text = ds.Tables("Contacts").Rows(baris).Item("Surname") End If End Sub 'Clear All TextBox when we want to add new data Private Sub ClearAllTextBox() txtID.Clear() txtFirstName.Clear() txtSurname.Clear() End Sub

7.4 Code to display the first, previous, next or Last data in the table
'Display First Record if the table is not empty Private Sub btnFirst_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnFirst.Click If MaxRows > 0 Then If baris = 0 Then MsgBox("First Record") End If baris = 0 DisplayRecord() Else MsgBox("Empty Table") End If End Sub 'Display Previous Record if the table is not empty Private Sub btnPrevious_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnPrevious.Click If MaxRows > 0 Then If baris > 0 Then baris = baris - 1 Else MsgBox("First Record") End If DisplayRecord() Else MsgBox("Empty Table") End If End Sub 'Display Next Record if the table is not empty Private Sub btnNext_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnNext.Click If MaxRows > 0 Then If baris < MaxRows - 1 Then baris = baris + 1 Else MsgBox("Last Record!") End If DisplayRecord() Else MsgBox("Empty Table") End If End Sub

Students Note

'Display Last Record if the table is not empty Private Sub btnLast_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLast.Click If MaxRows > 0 Then If baris = MaxRows - 1 Then MsgBox("Last Record!") End If baris = MaxRows - 1 DisplayRecord() Else MsgBox("Empty Table") End If End Sub

Students Note

The code are related to four buttons: <<, <, > and >> button.

7.5 Code to Add new data


Adding a new record is slightly more complex. First, you have to add a new Row to the DataSet, and then commit the new Row to the Database. Three buttons are related to this process. These three buttons are Add/Insert, Commit and Cancel. Private Sub btnAdd_Click code: Private Sub btnAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click btnAdd.Enabled = False btnCommit.Enabled = True btnCancel.Enabled = True btnSearch.Enabled = False btnUpdate.Enabled = False btnDelete.Enabled = False btnClose.Enabled = False btnFirst.Enabled = False btnPrevious.Enabled = False btnNext.Enabled = False btnLast.Enabled = False txtID.Enabled = True ClearAllTextBox() End Sub

Private Sub btnCommit_Click code:


Private Sub btnCommit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCommit.Click 'The first line is an If Statement. 'We're just checking that there is a valid record to add. If baris <> -1 Then Dim cb As New OleDb.OleDbCommandBuilder(da) Dim dsNewRow As DataRow Dim Sama As Boolean = False dsNewRow = ds.Tables("Contacts").NewRow() 'Make sure the input ID is a number. If IsNumeric(txtID.Text) And txtFirstName.Text <> "" _ And txtSurname.Text <> "" Then 'Make sure the input ID (Primary Key) is not duplicated. If MaxRows > 0 Then baris = 0 Do While (baris < MaxRows And Not Sama) If ds.Tables("Contacts").Rows(baris).Item("ID") = txtID.Text Then Sama = True End If baris = baris + 1 Loop End If If Not Sama Then dsNewRow.Item("ID") = txtID.Text dsNewRow.Item("FirstName") = txtFirstName.Text dsNewRow.Item("Surname") = txtSurname.Text 'Add new row in the table ds.Tables("Contacts").Rows.Add(dsNewRow) 'Update jumlah record atau baris dalam table MaxRows = MaxRows + 1 'Update the table in the database da.Update(ds, "Contacts") MsgBox("New Record added to the table")

Students Note

btnAdd.Enabled = True btnCommit.Enabled = False btnCancel.Enabled = False btnSearch.Enabled = True btnUpdate.Enabled = True btnDelete.Enabled = True btnClose.Enabled = True btnFirst.Enabled = True btnPrevious.Enabled = True btnNext.Enabled = True btnLast.Enabled = True txtID.Enabled = False 'display the last record baris = MaxRows - 1 DisplayRecord() Else MsgBox("The ID is duplicated") End If Else MsgBox("The ID should be Integer Number and No Empty TextBox") End If End If End Sub

Students Note

Private Sub btnCancel_Click code:


Private Sub btnCancel_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCancel.Click btnAdd.Enabled = True btnCommit.Enabled = False btnCancel.Enabled = False btnSearch.Enabled = True btnUpdate.Enabled = True btnDelete.Enabled = True btnClose.Enabled = True btnFirst.Enabled = True btnPrevious.Enabled = True btnNext.Enabled = True btnLast.Enabled = True txtID.Enabled = False 'If the table has any records then display one record If MaxRows > 0 Then baris = 0 DisplayRecord() Else ClearAllTextBox() End If End Sub

Students Note

7.6 Code to Search data


'Search Private Sub btnSearch_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSearch.Click Dim SearchID As String Dim dijumpai As Boolean = False If MaxRows > 0 Then SearchID = InputBox("Enter ID to find the person: ", "Search") If SearchID <> "" Then If IsNumeric(SearchID) Then baris = 0 Do While (Not dijumpai And baris < MaxRows) If ds.Tables("Contacts").Rows(baris).Item("ID") = SearchID Then dijumpai = True Else baris = baris + 1 End If Loop If dijumpai Then DisplayRecord() Else MsgBox("The person doesnot exist in the table") End If Else MsgBox("The ID should be Integer number") End If Else MsgBox("The ID is empty") End If Else MsgBox("Empty Table") End If End Sub

Students Note

7.7 Code to Update data


'Update Record if the table is not empty Private Sub btnUpdate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnUpdate.Click If MaxRows > 0 Then 'Variable that will be needed to update data Dim cb As New OleDb.OleDbCommandBuilder(da) If txtFirstName.Text <> "" And txtSurname.Text <> "" Then ds.Tables("Contacts").Rows(baris).Item("FirstName") = txtFirstName.Text ds.Tables("Contacts").Rows(baris).Item("Surname") = txtSurname.Text 'Update the record da.Update(ds, "Contacts") MsgBox("Data updated") Else MsgBox("Make sure all textboxes are not empty") End If Else MsgBox("Empty Table") End If End Sub

Students Note

7.8 Code to Delete data


'Delete a record Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click Dim cb As New OleDb.OleDbCommandBuilder(da) If MaxRows > 0 Then If MessageBox.Show("Do you really want to Delete this Record?", _ "Delete", MessageBoxButtons.YesNo, _ MessageBoxIcon.Warning) = DialogResult.No Then MsgBox("Operation Cancelled", MsgBoxStyle.Information, "Cancel") Exit Sub End If ds.Tables("Contacts").Rows(baris).Delete() 'Update the table in the database da.Update(ds, "Contacts") ClearAllTextBox() MsgBox("One record has been deleted", _ MsgBoxStyle.Information, "Deleted One Record") 'Jumlah record berkurang satu --> MaxRows juga berkurang satu: MaxRows = MaxRows - 1 'Check whether the table still has a record to be displayed If MaxRows > 0 Then baris = 0 DisplayRecord() End If Else MsgBox("Empty Table") End If End Sub

Students Note

7.9 Code to Quit Application


'Quit from Application Private Sub btnClose_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnClose.Click Me.Close() End Sub

Students Note

You might also like