Date post: | 29-Nov-2015 |
Category: |
Documents |
Upload: | weihang-wong |
View: | 50 times |
Download: | 2 times |
TABLE OF CONTENTS
CHAPTER 1: INTRODUCTION TO DATABASE AND MICROSOFT ACCESS 2007 ........................ 2
1.1 Relational Database Elements............................................................................................................ 3
1.2 Relationship within a Database .......................................................................................................... 5
1.3 Database Management System (DBMS) ............................................................................................ 6
1.4 Introduction to Access 2007 ............................................................................................................... 7
CHAPTER 2 : STRUCTURED QUERY LANGUAGE ........................................................................... 13
2.1 SQL Data Types ................................................................................................................................. 15
2.2 SQL as Data Definition Language .................................................................................................... 15
2.3 SQL as Data Manipulation Language .............................................................................................. 17
2.4 SQL as Data Query Language .......................................................................................................... 19
CHAPTER 3: DATABASE PROGRAMMING USING OLEDB TECHNIQUE ..................................... 26
3.1 Database Connectivity ...................................................................................................................... 27
3.2 Database Manipulation & Query ....................................................................................................... 33
CHAPTER 4: DATABASE PROGRAMMING USING ADODB TECHNIQUE .................................... 58
4.1 Step 1 : Creating the database ......................................................................................................... 59
4.2 Step 2 : Designing application interface ......................................................................................... 61
4.3 Step 3 : Adding project components ............................................................................................... 66
4.4 Step 4 : Variable declaration............................................................................................................. 67
4.5 Step 5 : Connection String & Data Source ...................................................................................... 68
4.6 Step 6 : Connection State ................................................................................................................. 68
4.7 Step 7 : Form Code ............................................................................................................................ 69
CHAPTER 5: DATA REPORTING USING REPORT VIEWER .......................................................... 79
5.0 DATA REPORTING USING REPORT VIEWER ............................................................................. 80
5.1 Creating DataSet ................................................................................................................................ 80
5.2 Creating Report ................................................................................................................................. 82
5.3 Creating Microsoft Report Viewer .................................................................................................... 90
Database Programming Using Access 2007 & Visual Studio 2008
[2]
CHAPTER 1:
INTRODUCTION TO
DATABASE AND
MICROSOFT ACCESS
2007
After you have completed this
chapter, you should be able to :
Define the basic
definition of database
and relational
database elements
Explain three types of
relationship in
relational database
and know how to
create relationship
within a database
Explain the basics of
database
management
software (DBMS)
Database Programming Using Access 2007 & Visual Studio 2008
[3]
1.0 INTRODUCTION TO DATABASE & MICROSOFT ACCESS 2007
atabase is an integrated collection of related files, records and data. It also can be defined as an
organized collection of data in an integrated place where it can be accessed and managed
systematically and can be accessed by multiple users at the same time. Database is a unique
concept on how to manage data structures in an organized and integrated fashion.
One of the most popular databases handling method today is relational database system. Relational
database handles all data in a tabular form. All information is being kept in a table that consist of columns
and rows.
Below are the important elements of a relational database model:
1.1 Relational Database Elements
a. Table
Table is considered as the main building block of a database. It is a set of data elements which
is organized in columns and rows. Each column represents an attribute which is called field.
Examples of tables are Student, Employee, Sales, Purchase and Subject.
b. Field
Column in table is also called as field. Each field has a distinct name and is used to store
different element of a data. Each field will have different type of data format. Examples of field
are Student_Name, Student_Matric, Student_Address, Employee_Status, Sales_Date and
many others.
c. Record
Table row represents data value for an item. Each row has its own data value and is referred
as record in tables. Examples of record are ‘10111’, ‘10113’ for Student_Matric field,
‘Ali’,’Rajinikanth’ and ‘Andy Lau’ for Student_Names
d. Keys
A key is an attribute (field) that determine other attributes. It is used to uniquely identify each
record in database tables. Keys are also important because it is used to establish relationship
between tables and to ensure the integrity of the data. Examples of keys are Student_Matric
for Student table, Employee_ID for Employee table and Sales_ID for Sales table.
D
Record
Field/Column
Figure 1: Table Example
Database Programming Using Access 2007 & Visual Studio 2008
[4]
Keys can be divided to primary key, foreign key, superkey, candidate key and secondary keys,
however, in this topic the discussion will only be limited to primary key and foreign key only.
Primary key is the main key in table to uniquely identify each record. Normally it comprises of
single field, but there are cases which primary key comprises of more than two fields.
Foreign key is the key used in defining relationship between tables. It is the primary key from
the referenced master table. The value between the two related fields must match each other.
A table can have many foreign key, depending on the table which it related to.
In the example above, Department_Code and Manager_ID is the primary key in the table
Department and table Manager. While in the table Manager, Department_Code act as the
foreign key. The concept of relationship between entities and tables will be explained in detail
in the topic Relationship within a Database.
Figure 2: Primary and Foreign Key Example
Database Programming Using Access 2007 & Visual Studio 2008
[5]
1.2 Relationship within a Database
a. 1 : 1 (One To One)
1: 1 relationship rarely happens in database design. It happens when one entity is related with
only one other entity and the other way round. In this relationship only one occurrence of the
related record in the related tables happens.
Example of 1:1 relationship is the relation between Employee and Authentication. One
employee can own one authentication id only and one id can be owned by only one employee.
b. 1 : M (One To Many)
1:M relationship is the common relation that happen in relational database. This type of relation
happens when one record in the master table is related with many records in the child table. It
is linked by using foreign key in the child table. Note that the foreign key is the primary key
from the master table.
Example of 1: M relationship is the relationship between book and shelf. One book can be
located in only one shelf while one shelf can locate many books. Another example is between
Voucher and Cheque. One voucher can produce many cheques while one cheque can be
produced by only one voucher.
Figure 4: One To Many Relationship
Figure 3: One To One Relationship
Database Programming Using Access 2007 & Visual Studio 2008
[6]
c. M : M (Many To Many)
M:M relationship refers to relation when many records also related with many records in the
related table. In the case of M:M relationship which can be implemented directly, an
intermediate entity has to be created. This intermediate entity will consist of primary key from
both of the related table and also other fields which are required in the relationship.
Example of many to many relationship is Student and Subject. One student can take many
subjects and in the same time one subject can be taken by many students. In this case,
intermediate entity has to be created. The name of the intermediate entity can be the
combination of the two tables or other names which are appropriate.
1.3 Database Management System (DBMS)
DBMS is a complex software programs that can be used to organize and manage a database. It
acts as middleware between users and database. The main function of DBMS are to create
database and its elements such as tables and index, define relationship between tables, perform
data retrieval and data query using query language, administer its users and security and produce
reports.
There are a lot of DBMS vendors in the market such as MySQL (open source), Oracle (Sun),
SQLServer (Microsoft), PostgreSQL (open source), DB2 (IBM) Informix (IBM) and many more.
Each type of DBMS has their own specialty and specific purposes, for example, IBM Informix is
Figure 5: Many To Many Relationship
Data Query
Relational
Database
Structure
End Users
End Users
DBMS (Database
Management System) End User Data Request
Figure 2: DBMS relates end user and database structure
Database Programming Using Access 2007 & Visual Studio 2008
[7]
meant to focus on online transaction processing while MySQL is an open source database software
for middle size application.
One of the popular DBMS for students and small medium size organization that use Windows
platform is Access from Microsoft Corporation. Access is one of the software included in the
Microsoft Office suite and is highly used around the world because of its simplicity and friendly user
interface. In this book, Microsoft Access 2007 will be used as the main database.
1.4 Introduction to Access 2007
Microsoft Access is an application used to create small and midsize computer desktop databases
for Microsoft Windows family of operating systems. Starting with version 1.0 in 1992, Access DBMS
continue to expand with lots of new and exciting functionalities to manage database from time to
time. Figure below shows the evolution of Access from 1992 until now. The latest version of Access
comes in Microsoft Office 2007 suite and is also known as Access 2007.
The new version of Access 2007 uses different extension which is .accdb compared to prior version
which use .mdb. The new format enables Access to handles multi value and attachment in fields.
Access 2007 offers a totally different environment compared to previous version but it still maintains the
basic features of Access which are creating tables, queries, forms and reports by using design mode or
wizard. Advanced users can use and VBA (Visual Basic for Application) to enhance the Access
application.
Database Programming Using Access 2007 & Visual Studio 2008
[8]
Besides the core function, there are lot more functionalities such as user administration, maintaining
securities, switchboard and many more. One of the major upgrade in Access 2007 is its interface where
it uses the ribbon concepts that contains iconic like toolbar to create database elements. Each icon has
its own functionalities.
In this module, you are going to create an Access 2007 file to store your data while Visual Basic 2008
will serve as the interface of your database system. The discussion of Access will only be limited to the
creation of tables because queries, form and report will be created by using Visual Basic 2008 and
crystal report.
1.4.1 Create New Database File.
1. Start Microsoft Access 2007
2. Click New Blank Database icon
3. Enter Sales as the file name to replace the default name (Database1).
4. Select the directory where you want to save your file by clicking the folder icon.
(The default directory is My Document folder) and click Create button.
Database Programming Using Access 2007 & Visual Studio 2008
[9]
1.4.2 Creating Tables
Table is the most important components of any relational database. Data in database
is stored in tables in a form of columns and row. Table column represents the data
characteristics which is known as field while table rows represents data item and is
known as record.
To create a table, click table on the create tab. You can choose either to use the
normal table view or use table templates or straight away use table design which will
open the classic design mode.
When table had been created, it will appear in datasheet view. In this mode, you can
add delete or update fields, modify the formatting, set null properties, create a lookup
column and update the table name.
Database Programming Using Access 2007 & Visual Studio 2008
[10]
Instead of using datasheet view, classic design view can also be used to modify the
table structure.
Design view in 2007 still maintains the classic view of design mode which allows user
to create the fields in rows. When adding fields to the table structure, few things has
to be considered and carefully set up. The first one is the data type. Choose suitable
data type for each field based on its usage. Table below shows the important data
types in Access and its description.
Data Type Description Example
Text Text character up to 255 character Names
Memo Up to 65300 alphanumeric characters
Address, notes
Number Numeric value Matrix number, Quantity
Date/Time Date and time Sales date
Currency Currency value Sales price
Auto Number Unique auto generated sequence numbers
Transaction number
Attachment Any binary file such as images and office file
Digital images
As stated earlier, this module will only discuss the creation of tables in Access; other
Access features will not be discussed. This is because query, form and report handling will
be done through Microsoft Visual Basic 2008.
Database Programming Using Access 2007 & Visual Studio 2008
[11]
Chapter Exercises
Create the following tables in Sales database:
1. Table Name: Product
Field Name Data Type
ProductCode Text
ProductName Text
Brand Text
Model Text
Price Number
2. Table Name: Customer
Field Name Data Type
CustID Text CustName Text
Address Text
Phone Text
Email Text
3. Table Name: SalesOrder
Field Name Data Type
SONo Text
OrderDate Date/Time
CustID Text
ProductCode Text
Quantity Number
Database Programming Using Access 2007 & Visual Studio 2008
[13]
CHAPTER 2 :
STRUCTURED QUERY
LANGUAGE
After you have completed this
chapter, you should be able to :
Define the basic of SQL
Differentiate between
SQL and other
programming languages
Apply the basic command
of SQL data definition,
data manipulation and
data query language.
Database Programming Using Access 2007 & Visual Studio 2008
[14]
2.0 STRUCTURED QUERY LANGUAGE
QL is an independent language that enables users to define database structures, manipulate its
content, perform data query and database administration. SQL is independent in nature because all
DBMS vendor use the same SQL standard. SQL is not a programming language, but it serves as a
specific language to manage data and perform data retrieval from any type of relational database.
Tracking down the history of SQL down the memory lane, we will found out that this powerful language was
developed at IBM laboratory by Donald Chamberlin and Raymond Boyce in 1972. In the early days, it is
called as SEQUEL and its functionality is limited to perform data retrieval only in the IBM relational database
environment.
Knowing its potential and future use, SEQUEL was later then standardized by ANSI (American National
Standard Institute) and the name was changed to SQL and pronounced as SEQUEL or ES QUE EL. Even
though SQL had been standardized by ANSI, there are many different versions of the SQL language
depending on the DBMS programs.
SQL is a standard language that only can be used to manage database and perform data retrieval only, not
more than that. SQL cannot be used to perform tasks that can be done by other programming languages
such as creating forms, button, handling exceptions and perform loop.
Because of these limitations, SQL has to be used with other third party programming languages or DBMS
tools such as C++, Java, ASP.Net, PHP, Visual Basic, Microsoft Access, MySQL, SQL Server and many
more.
SQL functionalities can be divided into three categories which are data definition, data manipulation and
data retrieval.
S
Relational
Database
Structure
End Users
End Users
DBMS (Database
Management System)
SQL
Database Programming Using Access 2007 & Visual Studio 2008
[15]
2.1 SQL Data Types
Data types for SQL refer to the length and type of the field which is going to be created. SQL data
types are declared together with the database table structure. Below is the common data type that
is used in declaring table structure.
GROUP DATA TYPE USAGE
CHARACTER NUMBER (Long, Decimal) Numbers with specific length and decimal places
INTEGER Numbers without decimal places
NUMBER CHAR (Long) Fixed sized character up to 255 characters.
VARCHAR (Long) Varying size character
DATE DATE Dates in any format
TIME Time in any format
However, this data type is only common when standard SQL is used. Different vendors such as
Access and MySQL provide much more option such as CURRENCY, AUTONUMBER and many
more.
2.2 SQL as Data Definition Language
SQL can be used as a language to define a database. This includes the creation of database, the
creation of database objects such as tables, indexes and views and also performing administration
function on a database such as handling user access, table maintenance and setting up the
primary key for tables.
The basics of data definition language can be divided into three segments which are:
2.2.1 CREATE
Creates database components such as tables, indexes (search key), primary key and
views and also is used to create the database schema.
Examples:
CREATE TABLE Product
[field name] [data type] [constraint]
P_Code INTEGER NOT NULL UNIQUE,
P_Name VARCHAR (50) NOT NULL,
P_Price NUMBER (7,2) NOT NULL
This statement will create the following table structure
Database Programming Using Access 2007 & Visual Studio 2008
[16]
2.2.2 ALTER
Modify existing database components structure such as add new field in table.
Examples:
ALTER TABLE Product
ADD P_Type CHAR(10) NOT NULL ,
ALTER TABLE Product
DROP COLUMN P_Type
2.2.3 DROP
Delete existing database components and is rarely used. This command is normally
used to delete users or table in database.
Examples:
DROP TABLE Product
In this book, data definition language will not be used together with Visual Basic 2008. This is
because most functions of DDL can be done effectively by using Access 2007 interface such as
table creation, altering and deleting tables.
Database Programming Using Access 2007 & Visual Studio 2008
[17]
2.3 SQL as Data Manipulation Language
SQL data manipulation commands deals with the manipulation of data in database tables. Data
manipulation commands in SQL involve three important tasks which are:
2.3.1 Data Insertion
Data insertion command is used to insert new row (records) in a table by using the
INSERT INTO statements. INSERT INTO statements can be written in two options,
the first option is by specifically addressing the field names and the value that will be
inserted in the columns.
Examples:
[table] [table fields] [values]
INSERT INTO Product (P_Code, P_Name) VALUES (‘001’, ‘Pen’)
The second option of writing INSERT INTO statement doesn’t specify the specific
field to be inserted; only their values will be specified. This option is suitable when all
table fields are going to be given a value.
INSERT INTO Product VALUES (‘001’, ‘Pen’, ‘RM1’)
2.3.2 Data Update
Data update command is used to update existing records in table by using the
UPDATE SET statement.
Examples:
UPDATE Product SET P_Name = ‘Pencil’
UPDATE statement must be used together with the WHERE statement, otherwise, all
records in a table will be updated, in these case, all P_Name records in the table will
be changed to ‘Pencil’. The WHERE statement is a special syntax in SQL that is used
to filter records.
UPDATE Product SET P_Name = ‘Pencil’ WHERE P_Code = ‘001’
The above UPDATE statement will only changed the record where P_Code is equal
to ‘001’ only.
Database Programming Using Access 2007 & Visual Studio 2008
[18]
2.3.3 Data Delete
Data deletion command is used to delete existing records in table by using the
DELETE statement.
Examples:
DELETE FROM Product
DELETE statement must be used together with the WHERE statement, otherwise, all
records in the table Product will be deleted and this operation cannot be undo.
DELETE FROM Product WHERE P_Code = ‘001’
Database Programming Using Access 2007 & Visual Studio 2008
[19]
2.4 SQL as Data Query Language
Querying is considered as the most important and common function of SQL. The basic of querying
in SQL use SELECT statement to perform data retrieval from database tables. The results of
SELECT statement is stored in a temporary data reader such as record set (VB 2008) or result set
which also have the same structure in a form of rows and columns.
SQL SELECT statement can be used in a variety of ways and can be combined with multiple
functionalities. That’s why SELECT statement is considered as the most powerful statement in SQL
language.
2.4.1 Basic SELECT
Below is the ‘Product’ table
In order to select P_Code and P_Name from the table above, the SELECT statement
will look like :
SELECT P_Code, P_Name FROM Product
The results will be:
To retrieve all columns, use SELECT with *
SELECT * FROM Product
All columns will be selected.
Database Programming Using Access 2007 & Visual Studio 2008
[20]
2.4.2 SELECT with WHERE
As mentioned before, WHERE statement is used to filter results or in SQL statement.
WHERE statement can be used together with UPDATE, DELETE and SELECT
statement as demonstrated in the UPDATE and DELETE examples.
SELECT statement below will retrieve data where the product type is equal to ‘Pencil’.
SELECT P_Code, P_Name FROM Product WHERE P_Type = ‘Pencil’
Below is the list of operations that can be used with WHERE
Operator Descriptions Examples
= Equal SELECT * FROM Product WHERE P_Type= ‘Pencil’
>,< Greater/smaller than SELECT P_Price FROM Product WHERE P_Price > RM 1
<> Not equal to SELECT * FROM Product WHERE P_Type <> ‘Pencil’
>=,<= Greater/smaller than or equal SELECT P_Price FROM Product WHERE P_Price > RM 1
LIKE Pattern search SELECT * FROM Product WHERE P_Type LIKE ‘Pen%’ *The result will display the list of records which the product type starts with Pen.... This means Pen and Pencil will be listed in the result set. *The % can also be used in front of the character for example %cil. In this case, the result will list product type which ends with the character ‘cil’.
BETWEEN Range search SELECT * FROM Product WHERE P_Price BETWEEN RM1 and RM1.50 *The result of the statement will display the result where product price in within the range of RM1 to RM 1.50 *BETWEEN can also be used to find range between characters, date and numbers.
Database Programming Using Access 2007 & Visual Studio 2008
[21]
WHERE statement can also be used with AND and OR conditions.
SELECT P_Code, P_Name FROM Product WHERE P_Type = ‘Pencil’ OR P_Type =
‘Pen’
The statement above will display the product code and name where the type is either
‘Pen’ or ‘Pencil’.
SELECT P_Code, P_Name FROM Product WHERE P_Type = ‘Pencil’ AND P_Price
= RM 1.00
The statement above will display the record which the type is equal to Pencil and the
price is equal to RM 1.00.
2.4.3 SELECT with ORDER BY
Although simple in nature, ORDER BY is one of the most useful functions of SQL.
ORDER BY can be used to sort records in ascending or descending mode. ORDER
BY statement located at the end of SELECT statement.
SELECT * FROM Product ORDER BY P_Code Asc
ASC stands for ascending order by DESC stands for descending order.
Database Programming Using Access 2007 & Visual Studio 2008
[22]
2.4.4 SELECT with FUNCTIONS
SQL has many useful functions that can be used either to perform calculations, string
operations or formatting. Below is the list of some useful SQL functions that can be
used together with SELECT statement.
Functions Descriptions Examples
AVG Calculate average SELECT AVG (P_Price) AS AvgPrice FROM Product
SUM Accumulate sum SELECT SUM (P_Price) AS SumPrice FROM Product
COUNT Count number of records SELECT COUNT (*) AS RecCount FROM Product
MAX Find maximum value SELECT MAX (P_Price) AS MaxPrice FROM Product
MIN Find minimum value SELECT MIN (P_Price) AS MinPrice FROM Product
FIRST Search for first value SELECT FIRST (P_Code) AS FirstCode FROM Product
LAST Search for last value SELECT LAST (P_Code) AS LastCode FROM Product
2.4.5 SELECT with GROUP BY
The GROUP BY statement is very useful in grouping the result set in one or more
columns. GROUP BY statement is normally used with aggregate functions.
P_Id PurchaseDate PurchasePrice Customer
1 2008/11/12 1000 Hisham
2 2008/10/23 1600 Hadzrami
3 2008/09/02 700 Hisham
4 2008/09/03 300 Hisham
5 2008/08/30 2000 Raudah
6 2008/10/04 100 Hadzrami
GROUP BY statement can be used in the above situation to group the result for example to find the total purchase of each customer.
SELECT Customer,SUM(PurchasePrice) FROM Purchases GROUP BY Customer
The result-set after the SQL statement had been executed will look like this:
Customer SUM(PurchasePrice)
Hisham 2000
Hadzrami 1700
Raudah 2000
Database Programming Using Access 2007 & Visual Studio 2008
[23]
Chapter Exercise :
The contents of Product table are as follows:
Product
Code Name Model Siz
e QtyOnHand
Reorder
Qty
Pric
e Vendor
2407WF
P
Ell 24" 2407WFP TFT LCD Monitor Ell 24 6 2 249
9
ABC S/B
AL2216
W
Acer 22" AL2216W LCD Monitor Acer 22 3 2 129
9
M Ent
BFP73
G
BenQ 17" FP73G+ TFT LCD Monitor BenQ 17 2 2 599 M Ent
BFP92
W
BenQ 19" FP92W TFT LCD Monitor BenQ 19 5 2 639 M Ent
E156FP Ell 15" E156FP TFT LCD Monitor Ell 15 1 2 499 ABC S/B
E177FP Ell 17" E177FP TFT LCD Monitor Ell 17 5 2 569 ABC S/B
L1752S LG 17" L1752S TFT LCD Monitor LG 17 1 2 575 HMP S/B
L1753S LG 17" L1753S TFT LCD Monitor LG 17 5 2 599 HMP S/B
L1952S LG 19" L1952S TFT LCD Monitor LG 19 4 2 709 HMP S/B
S732N Samsung Syncmaster 732N - 17"
Monitor
Samsung 17 5 2 599 XYZ Ent.
S740N Samsung Syncmaster 740N - 17"
Monitor
Samsung 17 8 2 575 XYZ Ent.
S932B Samsung Syncmaster 932B - 19"
Monitor
Samsung 19 4 2 835 XYZ Ent.
S940B
W
Samsung Syncmaster 940BW - 19"
Monitor
Samsung 19 6 2 810 XYZ Ent.
VA912B Viewsonic VA912B 19" TFT Monitor Viewsonic 19 1 2 799 ABC S/B
Database Programming Using Access 2007 & Visual Studio 2008
[24]
REQUIRED:
(a) Write the SQL code to display the 17” (inches) monitors that have reached or exceeded the
reorder quantity as shown in Query1 table below.
Query1
Name Model Price
BenQ 17" FP73G+ TFT LCD
Monitor
BenQ 599
LG 17" L1752S TFT LCD
Monitor
LG 575
(b) Write the SQL code to display the monitors which price is above RM1000 as shown in Query2
table below.
Query2
Name Model Price
Acer 22" AL2216W LCD Monitor Acer 1299
Ell 24" 2407WFP TFT LCD Monitor Ell 2499
(c) Write the SQL code to change the reorder quantity from 2 units to 3 units for all models.
(d) Write the SQL code to delete a record for monitor with the product code L1952S.
(e) Write the SQL code to insert the following data.
Code Name Model Siz
e QtyOnHand
Reorder
Qty
Pric
e Vendor
1999E Dell Studio Laptop Dell 14 7 3 249
9
MHS/AM
Database Programming Using Access 2007 & Visual Studio 2008
[26]
CHAPTER 3:
DATABASE
PROGRAMMING USING
OLEDB TECHNIQUE
After you have completed this
chapter, you should be able to:
Establish database
connection between
Visual Basic and Access
Perform database
manipulation and query
using VB and SQL
statement.
Use components such as
Data Grid and List View
to perform database
manipulation.
Database Programming Using Access 2007 & Visual Studio 2008
[27]
3.0 DATABASE PROGRAMMING USING OLEDB TECHNIQUE
3.1 Database Connectivity
In this part, we will learn about the objects that we can use to open and read data from a database. We
will be using MS Access 2007 as our database.
The Connection Object
We need to establish connection to a database before your application can manipulate the database
such data insertion, deleting, updating or searching. So we need a Connection Object to enable us to
connect to a database.
There are a number of different connection objects, and it depends largely on the type of database
you're connecting to. For our application, we will be using MS Access 2007 database, so we will need
something called the OLE DB connection object.
OLE stands for Object Linking and Embedding that allow you to connect to data sources in general, and
not just databases. You can use it, for example, to connect to text files, SQL Server, email, etc.
There are a number of different OLE DB objects (called data providers), because we are using Access
2007, so we will use "Microsoft.ACE.OLEDB.12.0". (Note: If you’re using MS Access 2003 version you
have to use Microsoft.Jet.OLEDB.4.0 data provider).
Database Programming Using Access 2007 & Visual Studio 2008
[28]
Establishing Database Connection
Let us begin our lesson on how to create connection to a database.
Create a new project and renamed it as OleDBExample.
Click File Save All, to save your project.
Browse the location you want to store your project.
Explanation: In this example, the project is saved inside My Documents folder. You can change the
location/directory where you want to save your project.)
Database Programming Using Access 2007 & Visual Studio 2008
[29]
Open your Windows Explorer and look for OleDBExample folder.
Double click the folder and you will see your folder as follows.
Now, we’re going to create/add Data folder inside bin folder.
Double click the bin folder, add a new folder and rename it as Data.
The next step is to copy your database file that you have created in the previous section into the Data
folder.
Find the Sales.accdb file in My Documents folder, right-click, cut the file and paste it inside the Data
folder.
You should be able to see Sales.accdb inside the Data folder.
Database Programming Using Access 2007 & Visual Studio 2008
[30]
Interface Design
Back to our Project, place a button on your form and set the Name and Text properties to LoadButton
and Load accordingly.
Double click your button to open up the code window. Add the following codes:
Const cnString As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = ..\Data\Sales.accdb"
Dim con As OleDb.OleDbConnection
con = New OleDbConnection(cnString)
con.Open()
MsgBox("A Connection to the Database is now open")
con.Close()
MsgBox("The Connection to the Database is now Closed")
Note: If you are using Access 2003, replace the first line with the following code:
Const cnString As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = ..\Data\Sales.accdb"
Database Programming Using Access 2007 & Visual Studio 2008
[31]
At the very top of your code window, before Public Class Form 1, type the following:
Imports System.Data.OleDb
Your coding window should now look like this:
Test out your code by running your program.
Click Load button and the following message boxes should display to show the connection to the database is
open. Click OK and you will see the second message box.
Troubleshooting: If the message box does not appear, make sure your Data Source path is correct. The
database file (Sales.accdb) should be located inside Data folder, Data folder should be located inside bin folder
and bin folder should be located inside OleDBExample folder as follows.
Database Programming Using Access 2007 & Visual Studio 2008
[32]
Explanation:
If we look at the code below, we will notice that there are two things stated in the Connection Object: the
technology to do the connecting to our database; and the location of the database. The technology is called the
Provider; and you use "Data Source" to specify where your database is.
Notice the two parts, separated by a semi-colon:
1st Part: PROVIDER= Microsoft.ACE.OLEDB.12.0 2nd Part: Data Source = ..\Data\Sales.accdb
The first part specifies which provider technology we want to use to do the connecting which is ACE (For Access 2003, the provider technology is Jet). The second part, typed after a semi-colon, points to where the database is. In the above code, the database is in the Data folder which is inside bin folder and inside OleDBExample (your project) folder. The name of the Access file we want to connect to is called Sales.accdb.
Database Programming Using Access 2007 & Visual Studio 2008
[33]
3.2 Database Manipulation & Query
In previous section, you have learned on how to establish connection to database. In the next section, we will
look into how to Insert, Update and Delete record.
Adding Project Module
We have seen that whenever the application wants to interact with the database, we need to establish the
database connection. Therefore, every form that we want to add into the project, which interact with the
database, must include the following code.
Const cnString As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = ..\Data\Sales.accdb"
Dim con As OleDb.OleDbConnection
con = New OleDbConnection(cnString)
In order to simplify the code, the best practice is, we add a module into our project and write the code which we
will be using repeatedly in the module.
Click Project Add Module
Rename the module name as ProjectModule and click Add.
Inside the module, add in the following line (Note: The statement should be in a single line and not three as it is
below):
Database Programming Using Access 2007 & Visual Studio 2008
[34]
Public Const conString As String = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source =
..\Data\Sales.accdb"
Public conn As OleDbConnection = New OleDbConnection(conString)
At the very top of your code window, before Module ProjectModule, type the following:
Imports System.Data.OleDb
Your coding window should now look like this:
Insert New Record.
Previously, you have created database named Sales.accdb with three tables, Product, Customer and
SalesOrder. So now, we are going to create a form that will serve as an interface for user to add new record into
the Product table.
Add new windows form and rename it as InsertProductForm.
Add five TextBox on the form as the number of fields in Product table is five. Set the Name properties as follows:
1. ProductCodeTextBox 2. ProductNameTextBox 3. BrandTextBox 4. ModelTextBox 5. PriceTextBox
Add three buttons; Save (Text: Save, Name: SaveButton), Clear (Text: Clear, Name: ClearButton) and Exit (Text:
Exit, Name: ExitButton).
Database Programming Using Access 2007 & Visual Studio 2008
[35]
Your form should looks as the following figure.
Double click Save button and write the following codes.
Dim sqlQRY As String = "INSERT INTO Product Values ('" & ProductCodeTextBox.Text & "', '" &
ProductNameTextBox.Text & "', '" & BrandTextBox.Text & "', '" & ModelTextBox.Text & "', '" & PriceTextBox.Text
& "' )"
Try
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand(sqlQRY, conn)
cmd.ExecuteNonQuery()
MsgBox("Record Inserted")
Catch ex As OleDbException
MsgBox("Error: " & ex.ToString & vbCrLf)
Finally
conn.Close()
End Try
Database Programming Using Access 2007 & Visual Studio 2008
[36]
At the very top of your code window, before Public Class InsertProductForm, type the following:
Imports System.Data.OleDb
Double click Clear button and write the following codes.
ProductCodeTextBox.Clear()
ProductNameTextBox.Clear()
BrandTextBox.Clear()
ModelTextBox.Clear()
PriceTextBox.Clear()
ProductCodeTextBox.Focus()
Double click Exit button and write the following code.
Me.Close()
Your coding window should now look like this (Only part of the Sql statement can be seen, the whole Sql
statement (above) should be entered in a single line):
Database Programming Using Access 2007 & Visual Studio 2008
[37]
Finding/Searching Record
Another important component in database is a search function. In this example, we’re going to create a new form
to search record in the Product table based on the Product Code entered by the user.
Create a new windows form and name it as SearchForm. Design your form and set the properties as follows:
1. ProductCodeTextBox 2. ProductNameTextBox 3. BrandTextBox 4. ModelTextBox 5. PriceTextBox
Create a Search button and name it as SearchButton.
Double-click it and enter the following codes:
Dim ResultString As String
Dim sqlQRY As String = "SELECT * FROM Product WHERE ProductCode = '" & ProductCodeTextBox.Text & "'"
Dim conn As OleDbConnection = New OleDbConnection(conString)
Try
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand(sqlQRY, conn)
Database Programming Using Access 2007 & Visual Studio 2008
[38]
Dim rdr As OleDbDataReader = cmd.ExecuteReader
While (rdr.Read)
ResultString = rdr("ProductCode").ToString()
NameTextBox.Text = rdr("ProductName").ToString()
BrandTextBox.Text = rdr("Brand").ToString()
ModelTextBox.Text = rdr("Model").ToString()
PriceTextBox.Text = rdr("Price").ToString()
End While
If ResultString <> ProductCodeTextBox.Text Then
MsgBox("Record Not Found")
CodeTextBox.Clear()
CodeTextBox.Focus()
End If
Catch ex As OleDbException
MsgBox("Error: " & ex.ToString & vbCrLf)
Finally
conn.Close()
End Try
Database Programming Using Access 2007 & Visual Studio 2008
[39]
At the very top of your code window, before Public Class SearchForm, type the following:
Imports System.Data.OleDb
Your coding window should now look like this (The Sql statement should be entered in a single line):
Now, we are going to add in another two buttons that are Update and Delete buttons. Create an Update and
Delete buttons and name them as UpdateButton and DeleteButton accordingly.
Database Programming Using Access 2007 & Visual Studio 2008
[40]
Double-click the UpdateButton and enter the following codes:
Dim sqlQRY As String = "UPDATE Product SET ProductName='" & NameTextBox.Text & "', Brand='" &
BrandTextBox.Text & "', Model='" & ModelTextBox.Text & "', Price='" & PriceTextBox.Text & "' WHERE
ProductCode='" & ProductCodeTextBox.Text & "'"
Try
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand(sqlQRY, conn)
cmd.ExecuteNonQuery()
MsgBox("Record successfully saved...", MsgBoxStyle.Information)
Catch ex As OleDbException
MsgBox("Error: " & ex.ToString & vbCrLf)
Finally
conn.Close()
End Try
Your coding window should now look like this (The Sql statement should be entered in a single line):
Database Programming Using Access 2007 & Visual Studio 2008
[41]
Double-click the DeleteButton and enter the following codes:
If MessageBox.Show("Do you really want to Delete this Record?", _
"Delete", MessageBoxButtons.YesNo, _
MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation Cancelled")
Exit Sub
End If
Dim sqlQRY As String = "DELETE FROM Product WHERE ProductCode='" & ProductCodeTextBox.Text & "'"
Try
conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand(sqlQRY, conn)
cmd.ExecuteNonQuery()
MsgBox("Record successfully deleted...", MsgBoxStyle.Information)
ProductCodeTextBox.Clear()
NameTextBox.Clear()
BrandTextBox.Clear()
ModelTextBox.Clear()
PriceTextBox.Clear()
Catch ex As OleDbException
MsgBox("Error: " & ex.ToString & vbCrLf)
Finally
conn.Close()
End Try
Database Programming Using Access 2007 & Visual Studio 2008
[42]
Your coding window should now look like:
Data Grid
We can use data grid object to perform database manipulation function such as Insert, Delete and Update.
Add a new form and name it as ProductDataGridForm.
Look for DataGridView object inside Data Toolbox and create the DataGridView onto the form.
Set the DataGridView Name properties as Product DataGridView.
Add a button onto the form, set it’s Name as SaveButton and it’s Text as Save.
Database Programming Using Access 2007 & Visual Studio 2008
[43]
At the very top of your code window, before Public Class ProductDataGridViewForm, type the following:
Imports System.Data.OleDb
Add the following codes after Public Class ProductDataGridViewForm
Dim da As OleDbDataAdapter
Dim ds As DataSet = New DataSet
Dim sqlQRY As String
Double click Save button and write the following codes:
da.Update(ds, "Product")
Now we need to add codes for form load event.
Double-click the form (be careful not to click the DataGridView object) and add the following codes:
sqlQRY = "SELECT * FROM Product"
Try
conn.Open()
da = New OleDbDataAdapter(sqlQRY, conn)
Dim cb As OleDbCommandBuilder = New OleDbCommandBuilder(da)
Database Programming Using Access 2007 & Visual Studio 2008
[44]
da.Fill(ds, "Product")
ProductDataGridView.DataSource = ds
ProductDataGridView.DataMember = "Product"
Catch ex As OleDbException
MsgBox(ex.ToString)
Finally
conn.Close()
End Try
Your coding window should now look like:
Database Programming Using Access 2007 & Visual Studio 2008
[45]
Test the code, by running the application. You will see the form as follow:
In this DataGridView form you will see two records that have been added earlier. You can do all the database
operation such as inserting new record, updating record deleting as if you are using MS Access table.
All database manipulation operation above will NOT have any effect on the records in the database, unless you
need click Save button.
Database Programming Using Access 2007 & Visual Studio 2008
[46]
List View
We will introduce to you another object that can retrieve and display all records from a database table, the
ListView object.
Before we add a new form into our project, we need to add the following code into our ProjectModule.
Public Enum FormState
adStateAddMode = 0
adStateEditMode = 1
End Enum
Public Sub FillListView(ByRef lvList As ListView, ByRef myData As OleDbDataReader)
Dim itmListItem As ListViewItem
Dim strValue As String
Do While myData.Read
itmListItem = New ListViewItem()
strValue = IIf(myData.IsDBNull(0), "", myData.GetValue(0))
itmListItem.Text = strValue
For shtCntr = 1 To myData.FieldCount() - 1
If myData.IsDBNull(shtCntr) Then
itmListItem.SubItems.Add("")
Else
itmListItem.SubItems.Add(myData.GetValue(shtCntr))
End If
Next shtCntr
lvList.Items.Add(itmListItem)
Loop
End Sub
Database Programming Using Access 2007 & Visual Studio 2008
[47]
Public Function ExecNonQuery(ByVal strSQL As String)
Dim conTable As OleDbConnection
conTable = New OleDbConnection
Try
With conTable
If .State = ConnectionState.Open Then .Close()
.ConnectionString = conString
.Open()
End With
Dim cmd As OleDbCommand = New OleDbCommand(strSQL, conTable)
cmd.ExecuteNonQuery()
Return True
Catch ex As OleDbException
Return ex
Finally
conTable.Close()
End Try
End Function
Database Programming Using Access 2007 & Visual Studio 2008
[48]
Public Function GetData(ByVal sSQL As String)
Dim cnTable As OleDbConnection
Dim sqlCmd As OleDbCommand = New OleDbCommand(sSQL)
Dim myData As OleDbDataReader
cnTable = New OleDbConnection(conString)
Try
cnTable.Open()
sqlCmd.Connection = cnTable
myData = sqlCmd.ExecuteReader
Return myData
Catch ex As Exception
Return ex
End Try
End Function
Your coding window should now look like:
Database Programming Using Access 2007 & Visual Studio 2008
[49]
Now, we will move to the next part, which is adding a new form and a ListView object.
Add a new windows form and rename it as ProductListForm.
Add the ListView object onto the form and rename it as ProductListView.
Add two buttons, Add and Delete and name them as AddButton and DeleteButton.
Database Programming Using Access 2007 & Visual Studio 2008
[50]
Double-click on the form (not the ListView object) to add the following codes:
sSql = "SELECT * FROM Product ORDER BY ProductCode ASC"
Call FillList()
At the very top of your code window, before Public Class ProductListForm, type the following:
Imports System.Data.OleDb
Declare the following variable after Public Class ProductListForm:
Dim sSql As String
Your coding window should now look like:
Database Programming Using Access 2007 & Visual Studio 2008
[51]
Now add the FillList sub procedure as follows:
Private Sub FillList()
With ProductListView
.Clear()
.View = View.Details
.FullRowSelect = True
.GridLines = True
.Columns.Add("Product Code", 100)
.Columns.Add("Product Name", 150)
.Columns.Add("Brand", 140)
.Columns.Add("Model", 130)
.Columns.Add("Price", 130)
FillListView(ProductListView, GetData(sSql))
End With
End Sub
Run your project and you get the following output (Note: The records in the ListView are the records you have
previously entered into your product table).
Database Programming Using Access 2007 & Visual Studio 2008
[52]
Next, we are going to add instructions for Delete button.
Double-click the Delete button and add the following codes:
Dim ProdCode As String
If MessageBox.Show("Do you really want to Delete this Record?", _
"Delete", MessageBoxButtons.YesNo, _
MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation Cancelled")
Exit Sub
End If
For Each sItem As ListViewItem In ProductListView.SelectedItems
ProdCode = sItem.Text
Next
If ProdCode <> "" Then
Dim strDeleted As Boolean
strDeleted = ExecNonQuery("DELETE Product.ProductCode FROM Product WHERE ProductCode= '" &
ProdCode & "'")
If strDeleted = "True" Then
MsgBox("Record's deleted.", MsgBoxStyle.Information)
Call FillList()
Else
MsgBox(strDeleted)
End If
Else
MsgBox("Please select record to delete.", MsgBoxStyle.Critical)
End If
Your coding window should now look like:
Database Programming Using Access 2007 & Visual Studio 2008
[53]
Run your project. First you need to select the record by clicking the record (click once, don’t double-click).
Click the Delete button and you will be prompted with the warning message.
Click Yes to proceed or No to cancel the operation.
Now, we will proceed with the Add button where we need to create a new form.
Create the following form and name it as ProductAddFromLV.
Database Programming Using Access 2007 & Visual Studio 2008
[54]
Set the following name properties for textboxes:
1. ProductCodeTextBox 2. ProductNameTextBox 3. BrandTextBox 4. ModelTextBox 5. PriceTextBox
Set the following name properties for buttons:
1. SaveButton 2. CloseButton
Double-click the Close button and type the following code:
Me.Close()
Double-click the Save button and type the following code:
Dim dt As DataTable = dsProduct.Tables("Product")
If ProductCodeTextBox.Text = "" Or ProductNameTextBox.Text = "" Then
MsgBox("Please fill up Product Code No or Name information.", MsgBoxStyle.Critical)
Exit Sub
End If
Try
If State = ProjectModule.FormState.adStateAddMode Then
Dim newRow As DataRow
newRow = dt.NewRow()
newRow("ProductCode") = ProductCodeTextBox.Text
newRow("ProductName") = ProductNameTextBox.Text
newRow("Brand") = IIf(BrandTextBox.Text = "", System.DBNull.Value, BrandTextBox.Text)
newRow("Model") = IIf(ModelTextBox.Text = "", System.DBNull.Value, ModelTextBox.Text)
newRow("Price") = IIf(PriceTextbox.Text = "", System.DBNull.Value, PriceTextbox.Text)
dt.Rows.Add(newRow)
Else
With dt
Database Programming Using Access 2007 & Visual Studio 2008
[55]
.Rows(0)("ProductCode") = ProductCodeTextBox.Text
.Rows(0)("ProductName") = ProductNameTextBox.Text
.Rows(0)("Brand") = IIf(BrandTextBox.Text = "", System.DBNull.Value, BrandTextBox.Text)
.Rows(0)("Model") = IIf(ModelTextBox.Text = "", System.DBNull.Value, ModelTextBox.Text)
.Rows(0)("Price") = IIf(PriceTextbox.Text = "", System.DBNull.Value, PriceTextbox.Text)
End With
End If
daProduct.Update(dsProduct, "Product")
MsgBox("Record successfully saved.", MsgBoxStyle.Information)
Catch ex As OleDbException
MsgBox(ex.ToString)
End Try
Your coding window should now look like:
Now, go back to ProductListForm and double-click Add button
Dim ProductAddFromLV As New ProductAddFromLV
Database Programming Using Access 2007 & Visual Studio 2008
[56]
ProductAddFromLV.State = ProjectModule.FormState.adStateAddMode
ProductAddFromLV.ShowDialog()
Call FillList()
Your coding window for Add button should now look like:
Now run the ProductListForm and click Add button.
Enter test data and click Save. You will be prompted with the message box saying record successfully saved.
Database Programming Using Access 2007 & Visual Studio 2008
[58]
CHAPTER 4:
DATABASE
PROGRAMMING
USING ADODB
TECHNIQUE
After you have completed this
chapter, you should be able to:
Establish database
connection between
Visual Basic and Access
using ADODB method
Perform database
manipulation and query
using VB and SQL
statement through
ADODB method and
components.
Database Programming Using Access 2007 & Visual Studio 2008
[59]
4.0 DATABASE PROGRAMMING USING ADODB (ActiveX Data Objects)
In the previous chapter, the concept of OLEDB was introduced. Examples on how to perform database
connection and manipulation is also explained by using the OLEDB technique. In this chapter, the concept
of ADODB will be used to demonstrate database connectivity and manipulation through examples.
Microsoft ActiveX Data Objects or widely known as ADODB is the latest version of earlier components such
as RDO (Remote Data Objects) and DAO(Data Access Objects) to perform data access to relational
database. ADODB can be said as a middleware between programming languages to database.
ADODB has three basic functionalities which are:
i. Establishing connection between programming languages and database. In this book, Visual Basic
is the programming languages and Access 2007 is used as the database.
ii. Data retrieval through the use of recordset. Recordset is used to store temporary data retrieved
from database through SQL query statement (SELECT).
iii. Perform changes to the database through SQL manipulation statement (INSERT, UPDATE,
DELETE).
In this chapter, step by step example on how to develop a simple database application will be explained. A
simple student registration system will be used as the example. This program will have one login form and
one main form that will act as the simple registration form.
4.1 Step 1 : Creating the database
The initial step in this project is to create the database and its object that is going to be used in the
programming project. Create a database and name it as dbADOExample
In the database, create the following tables.
Table Name : tblLogin
Field Name Data Type Size
UserName Text 255
UserPassword Text 255
UserLevel Text 255
Database Programming Using Access 2007 & Visual Studio 2008
[60]
Table Name: tblRegistration
Field Name Data Type Size
StudMatric Text 255
StudName Text 255
StudCourse Text 255
StudCollege Text 255
StudPhone Text 255
StudSem Number 255
Table Name: tblCourse
Field Name Data Type Size
CourseCode Text 255
CourseName Text 255
After all the tables had been created, fill in each table with these values:
tblLogin is related with tblRegistration in a 1:1 relationship. This is because one student can only
have one user name and one user name can be owned by only one user.
tblCourse is related with tblRegistration in a 1:M relationship. This is because one student can only
take one course and one course can be taken by many students.
Database Programming Using Access 2007 & Visual Studio 2008
[61]
4.2 Step 2 : Designing application interface
The second step is to create the application interface by using Visual Basic form. In this application,
four forms will be created which are:
i. frmLogin
frmLogin will be used to authenticate each user that is going to enter the system. If the
user is new to the system, they have to contact the system administrator to register their
user name and password. System administrator will register their names and level in the
administration form.
There will be two level of access; level 1 is the system administrator which is the super
user and level 2 is for normal user to view and modify their own data only.
User will have to enter their user name and password, if the password entered doesn’t
match the user name or the other way round, user will not be allowed to enter and a
warning message box will be displayed.
Set the properties of the objects as follows:
Object Property
User name and password text box
Name: txtUserName txtPassword
Password text box Password Char = *
Login and logout button Name: cmdLogin cmdLogout
Database Programming Using Access 2007 & Visual Studio 2008
[62]
ii. frmRegister
frmRegister will be used as the main form to register the details of the student. This form
contains toolbar to navigate between forms, a list to display existing data, a button to
perform search based on matric number and command buttons to execute SQL
statements.
More details on how this form is going to work will be explained more on later stages of
this chapter.
1
2
3
4
5
Database Programming Using Access 2007 & Visual Studio 2008
[63]
Set the properties of the object as follows:
Reference Object Property
1 Toolstrip Name: ToolStrip1 Items: Label1 Text : Admin Image Scaling : None TextImage Relation : ImageAboveText Label2 Text : Admin Image Scaling : None TextImage Relation : ImageAboveText Label3 Text : Admin Image Scaling : None TextImage Relation : ImageAboveText Images : any suitable icons for each of the items
2 Listview (must be associated with an image list)
Name: lstStudentList imageList1 (associated components) View: Details Small ImageList Imagelist1
3 Matric no, Name, Phone and Semester text box
Name: txtMatric txtName txtPhone txtSemester
4 Course and college combo box
Name: cmbCourse cmbCollege
5 Search, Insert, Update, Delete and Clear command button
Name: cmdInsert cmdUpdate cmdDelete cmdClear
Database Programming Using Access 2007 & Visual Studio 2008
[64]
iii. frmCourse
frmCourse will be used as the interface to the administrator to perform course
maintenance (add, delete or update course).
This form will consist of list displaying all course available and buttons to execute the SQL
statement.
Set the properties of the object as follows:
Object Property
Search, Course code and Course name text box
Name: txtSearch txtCourseCode txtCourseName
Insert, Update, Delete, Clear and Exit command button
Name: cmdInsert, cmdUpdate, cmdDelete, cmdClear cmdExit
Course listview Name: lstCourseList imageList1 (associated components) View: Details Small ImageList Imagelist1
Database Programming Using Access 2007 & Visual Studio 2008
[65]
iv. frmAdmin
frmAdmin will be used as the interface to the administrator to perform user maintenance
(add, delete or update user).
This form will consist of list displaying all users available and buttons to execute the SQL
statement.
Set the properties of the object as follows:
Object Property
Search, user name and user password name text box
Name: txtSearch txtUserName txtPassword
Insert, Update, Delete, Clear and Exit command button
Name: cmdInsert, cmdUpdate, cmdDelete, cmdClear cmdExit
Course listview Name: lstUserList imageList1 (associated components) View: Details Small ImageList Imagelist1
Database Programming Using Access 2007 & Visual Studio 2008
[66]
4.3 Step 3 : Adding project components
The third step involves establishing connections and database variables that is going to be used in
the project. All the connection properties and public variables will be stored in a module.
In order to create a module, click at the add new item icon and click at add module.
The default name for the module is Module1.vb, rename the module as dbConnection.vb to make it
more meaningful.
In order to use ADODB components, it has to be initialized, to do this, go to Project -> Add
Reference and click at adodb then click ok. This step is very important because adodb components
will not be feasible throughout the project if it’s not been initialized.
Database Programming Using Access 2007 & Visual Studio 2008
[67]
4.4 Step 4 : Variable declaration
By adding adodb components, we can use its object in this project, but before it can be used, it has
to be declared. Below are the list of adodb objects that is going to be used in the project and its
declaration. Note that all the declaration had to be done in the dbConnection module.
Object Description Declaration
Recordset Used to hold a set of records from database table in rows and columns format.
Public rec1 as ADODB.recordset
Connection Create a connection to database. Public con as ADODB.connection
Besides ADODB variables, there are also other variables that will be used throughout the project.
Below are the common variables that are used in a database programming project.
Description Data Type Declaration
Used to hold the connection string String Public strConnection as String
Used to hold SQL statement String Public strSQL as String
Used to hold user name, password and level field
String Public strUserName, strPassword, strLevel as String
All variable declaration should be done on the declaration section.
Database Programming Using Access 2007 & Visual Studio 2008
[68]
4.5 Step 5 : Connection String & Data Source
In order to create a connection with the database (in this case the database is dbADOExample),
the connection string and the data source has to be establish in the module.
Code Description Public Sub conn() Sub procedure header Con = New ADODB.Connection Initializing connection object Con.ConnectionString = "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\hishamuum\Documents\dbAdoExample.accdb"
Setting up the connection string provider. For Access 2007, the provider is Microsoft.Ace.OLEDB.12.0 Data source is the path where the database is being kept.
Con.Open() Opening the connection rec1 = New ADODB.Recordset Initializing recordset object End Sub Closing procedure header
Public rec1 As ADODB.Recordset
Public Con As ADODB.Connection
Public strConnection As String
Public strUserName As String
Public strPassword As String
Public strLevel As String
Public strSql As String
Public Sub conn()
Con = New ADODB.Connection
Con.ConnectionString =
"PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source =
C:\Users\hishamuum\Documents\dbAdoExample.accdb"
Con.Open()
rec1 = New ADODB.Recordset
End Sub
4.6 Step 6 : Connection State
When performing query, the connection state of recordset is important, each time a query is
executed, the recordset must be not be in active state. To ensure this, a procedure has to be
created and this procedure must be called each time a query is executed to ensure that the correct
state of the recordset is in place. The code is as below and also located in dbConnection module.
Public Sub checkConn()
If rec1.State = 1 Then rec1.Close()
End Sub
Database Programming Using Access 2007 & Visual Studio 2008
[69]
4.7 Step 7 : Form Code
4.7.1 frmLogin
There are two important events that has to be coded in the frmLogin. The first one is
form load event and the second would be the buttons click event.
Form Load:
Double click anywhere (except on the objects such as text box) on the form and form
load event header will be generated. In this event, call the procedure conn from the
dbConnection module by writing its name to establish the connection with the
database (dbADOExample.accdb).
Public Class frmLogin
Private Sub frmLogin_Load(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
conn()
End Sub
End Class
Login button:
Double click on top of the login button and the click event header for login button will
be generated.
Private Sub cmdLogin_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles cmdLogin.Click
End Sub
Validating the input
If txtUserName.Text = "" Or txtPassword.Text = "" Then
MsgBox("Incomplete Login Information, Please Try
Again")
Exit Sub
End If
The block of code above is to ensure system user cannot enter the system if the user
name or password text box is empty.
Database Programming Using Access 2007 & Visual Studio 2008
[70]
Retrieve user information to perform authentication
checkConn()
strSql = "SELECT * FROM tblLogin WHERE UserName='" &
txtUserName.Text & "'"
rec1.Open(strSql, Con, ADODB.CursorTypeEnum.adOpenStatic)
User information will be retrieved from the database where the user name entered in
the text box is similar with the user name from the table.
Code Description checkConn() Close the recordset strSql = "SELECT * FROM tblLogin
WHERE UserName='" &
txtUserName.Text & "'"
SQL statement to retrieve data from tblLogin
rec1.Open(strSql, Con,
ADODB.CursorTypeEnum.adOpenStatic) Execute the SQL statement
If rec1.Fields("UserName").Value = txtUserName.Text And
rec1.Fields("UserPassword").Value = txtPassword.Text Then
strUserName = rec1.Fields("UserName").Value
strPassword = rec1.Fields("UserPassword").Value
strLevel = rec1.Fields("UserLevel").Value
frmRegister.Show()
Me.Hide()
Else
MsgBox("Wrong Login Information, Please Try Again")
txtUserName.Text = ""
txtPassword.Text = ""
Exit Sub
End If
If the user name and password entered in the login menu match with the data from
the database, frmRegister will be displayed and the login information retrieved from
the database will be assigned to the global variables (strUserName, strPassword and
strLevel) to be used throughout the program
Code Description If rec1.Fields("UserName").Value =
txtUserName.Text And
rec1.Fields("UserPassword").Value
= txtPassword.Text Then
Matching the username and password entered by the user with the data extracted from tblLogin
strUserName
=rec1.Fields("UserName").Value
strPassword
=rec1.Fields("UserPassword").Value
strLevel
= rec1.Fields("UserLevel").Value
Assigning values from tblLogin to the global variable
frmRegister.Show()
Me.Hide() Hide the login form and displaying the frmRegister
MsgBox
("Wrong Login Information,
Please Try Again")
txtUserName.Text = ""
txtPassword.Text = ""
Displaying warning if login information wrongly entered
Database Programming Using Access 2007 & Visual Studio 2008
[71]
4.7.2 frmRegister
frmRegister is the most important form in this project. It contains the list of students
and has the functionalities to maintain the student information. The function of
frmRegister can be divided into two main categories, the first one is to display the
data on the objects and the second one would be maintaining the data (insert, update,
delete).
On top of the form is the toolbar which is used to navigate between forms in this
application. The code for the toolbar is as below (double click on each item on the
toolbar):
Private Sub ToolStripLabel1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ToolStripLabel1.Click
frmAdmin.Show()
End Sub
Private Sub ToolStripLabel2_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ToolStripLabel2.Click
frmCourse.Show()
End Sub
Private Sub ToolStripLabel3_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ToolStripLabel3.Click
End
End Sub
Database Programming Using Access 2007 & Visual Studio 2008
[72]
Displaying data retrieved from tables involves the use of two objects in this form. The
objects are listview and combo box.
Displaying data from tables in listview.
The listview on the left side of the form will be programmed two have two main
functionalities which are displaying the data from tblRegister and for user to select
records from the list. This is done by double clicking on specific record in the list.
Declare the variables that are going to be used. Declarations are being made at the
declaration section on top of the code window.
Private X As Integer
Private lst As ListViewItem
Private lvwColumn As ColumnHeader
Private shtCntr As Short
The variable X and shtCntr will be used as counters while lst and lvwColumn will be
used to store data list item and column header item.
Create a sub procedure to specifically handle the data retrieval and data loading
function into the list.
Private Sub loadList()
End Sub
Write all the code below in the above sub procedure.
Retrieve the data from tblRegister by using the following statements.
checkConn()
strSql = "SELECT StudMatric,StudName FROM tblRegister"
rec1.Open(strSql, Con, ADODB.CursorTypeEnum.adOpenStatic)
To generate the listview header based on fields from tblRegister, use the following
code.
ListView1.Clear()
For Me.shtCntr = 0 To 1
lvwColumn = New ColumnHeader()
lvwColumn.Text = rec1.Fields(shtCntr).Name
ListView1.Columns.Add(lvwColumn)
Next
Database Programming Using Access 2007 & Visual Studio 2008
[73]
Code Description ListView1.Clear() Clear the list view from past data For Me.shtCntr = 0 To 1 Determining the number of field to be
generated as column header. The index counter depends on the number of header to be displayed.
lvwColumn = New ColumnHeader()
lvwColumn.Text =
rec1.Fields(shtCntr).Name
ListView1.Columns.Add(lvwColumn)
Adding the field as the column header.
Next
After generating the header, next step is to fill the list with data retrieved from
tblRegistration using SQL statement. Use the following codes.
While Not rec1.EOF
lst = New ListViewItem
lst.Text = rec1.Fields(0).Value
For Me.X = 1 To 1
lst.SubItems.Add(rec1.Fields(X).Value)
Next X
rec1.MoveNext()
ListView1.Items.Add(lst)
End While
Code Description While Not rec1.EOF Navigate throughout the
recordset until end of record. lst = New ListViewItem
lst.Text = rec1.Fields(0).Value Initialize the listview and set the first item in the listview item
For Me.X = 1 To 1
lst.SubItems.Add(rec1.Fields(X).Value)
Next X
Adding subitems to the listview item.
End While End the loop when end of record reached in the recordset.
The final step to load the data into the list is to call the procedure from form load
event.
Private Sub frmRegister_Load(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
loadList()
End Sub
Database Programming Using Access 2007 & Visual Studio 2008
[74]
The loaded list will display data from tblRegistration.
Selecting Data from List
The next step is to write the code to select data from the list. Through this function,
user will be able to select any item from the list by double clicking on specific record.
Selecting data from the list will be done using the double click event of the list view.
Database Programming Using Access 2007 & Visual Studio 2008
[75]
The default event for the listview when it is being double clicked is
SelectedIndexChanged, to change this value, change the event to Double click.
Private Sub ListView1_DoubleClick(ByVal sender As Object,
ByVal e As System.EventArgs) Handles
ListView1.DoubleClick
End Sub
Fill in the sub procedure with the code below to retrieve the data selected and display
it in the text and combo boxes.
'retrieve the specific data selected from the list
checkConn()
strSql = "SELECT * FROM tblRegistration WHERE
StudMatric='" & ListView1.SelectedItems(0).Text & "'"
rec1.Open(strSql, Con, ADODB.CursorTypeEnum.adOpenStatic)
'assign each text boxes with specific fields
txtMatricNo.Text = rec1.Fields("StudMatric").Value
'assign studmatric variables with selected value(to be
used when performing update and delete
strStudMatric = txtMatricNo.Text
txtName.Text = rec1.Fields("StudName").Value
cmbCourse.Text = rec1.Fields("CourseCode").Value
cmbCollege.Text = rec1.Fields("StudCollege").Value
txtPhone.Text = rec1.Fields("StudPhone").Value
txtSemester.Text = rec1.Fields("StudSem").Value
Database Programming Using Access 2007 & Visual Studio 2008
[76]
Performing Data Manipulation
Performing data manipulation in this application involves the use of three important
SQL commands for data manipulation which are; INSERT, UPDATE and DELETE.
The data manipulation function will be done through the click event of command
button.
UPDATE & DELETE existing data
After selecting which data to be edited, the next process is to write the SQL statement
to execute the UPDATE operation. Double click cmdUpdate and cmdDelete Button
and write the following code:
Private Sub cmdUpdate_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
cmdUpdate.Click
strSql = "UPDATE tblRegistration SET StudName='"
& txtName.Text & "',StudPhone='" & txtPhone.Text
& "',StudSem='" & txtSemester.Text & "' WHERE
StudMatric='" & strStudMatric & "'"
Con.Execute(strSql)
loadList()
End Sub
Field involves in the update process are StudName, StudPhone and StudSem. strStudMatric variable which is retrieved when the list is selected is used as the condition. loadList() procedure is called to refresh the list each time UPDATE and DELETE statement is being executed.
Field involves in the update process are StudName, StudPhone and StudSem. strStudMatric variable which is retrieved when the list is selected is used as the condition in the UPDATE and DELETE statement. All text boxes is being cleared after the deletion process.
Private Sub cmdDelete_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
cmdDelete.Click
strSql = "DELETE FROM tblRegistration WHERE
StudMatric='" & strStudMatric & "'"
Con.Execute(strSql)
txtMatricNo.Text = ""
strStudMatric = ""
txtName.Text = ""
cmbCourse.Text = ""
cmbCollege.Text = ""
txtPhone.Text = ""
txtSemester.Text = ""
loadList()
End Sub
Database Programming Using Access 2007 & Visual Studio 2008
[77]
INSERT new data
Inserting new data to the table involves the use of SQL INSERT statement. Try the
following code to insert new data in the tblRegistration.
Private Sub cmdInsert_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
cmdInsert.Click
strSql = "INSERT INTO tblRegistration VALUES('" &
txtMatricNo.Text & "','" & txtName.Text & "','" &
cmbCourse.Text & "','" & cmbCollege.Text & "','" &
txtPhone.Text & "','" & txtSemester.Text & "','" &
txtName.Text & "')"
Con.Execute(strSql)
loadList()
End Sub
Performing data search
Data search is being done by entering the required matric no in the matric no text box
and then pressing the search button. Search function involves the use of SQL
SELECT statemement with condition (in this case matric no is the condition).
Double click the cmdSearch button and write the following code:
Private Sub cmdSearch_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
cmdSearch.Click
checkConn()
strSql = "SELECT * FROM tblRegistration WHERE
StudMatric='" & txtMatricNo.Text & "'"
rec1.Open(strSql, Con,
ADODB.CursorTypeEnum.adOpenStatic)
'assign each text boxes with specific fields
txtMatricNo.Text = rec1.Fields("StudMatric").Value
strStudMatric = txtMatricNo.Text
txtName.Text = rec1.Fields("StudName").Value
cmbCourse.Text = rec1.Fields("CourseCode").Value
cmbCollege.Text = rec1.Fields("StudCollege").Value
txtPhone.Text = rec1.Fields("StudPhone").Value
txtSemester.Text = rec1.Fields("StudSem").Value
End Sub
Database Programming Using Access 2007 & Visual Studio 2008
[78]
Chapter Exercise :
1. Complete the application by writing complete code for frmCourse and frmAdmin.
Database Programming Using Access 2007 & Visual Studio 2008
[79]
CHAPTER 5: DATA
REPORTING USING
REPORT VIEWER
After you have completed this
chapter, you should be able to :
Create a simple table
report
Apply data reporting
in Visual Basic 2008
using Report Viewer
Database Programming Using Access 2007 & Visual Studio 2008
[80]
5.0 DATA REPORTING USING REPORT VIEWER
Microsoft Report Viewer
This part shows how to create a simple table report based on the Sales database. You will add a report
template to your project, set up connection information for the Sales database, add a table data region, and
add a ReportViewer Windows Forms control to a Windows Form so the report can be viewed by users of the
application
5.1 Creating DataSet
Project Add New Item
In the Categories pane, choose Data.
In the Templates pane, choose DataSet.
In the Name box, type ProductDataSet and click Add.
Database Programming Using Access 2007 & Visual Studio 2008
[81]
View Server Explorer
Click at + Data Connections, Sales.accdb and Tables, so you will see the following figure.
Left click Product table (don’t release the mouse) and drag the Product table onto the design surface as
follows.
Database Programming Using Access 2007 & Visual Studio 2008
[82]
5.2 Creating Report
Project Add New Item
In the Categories pane, choose Reporting .
In the Templates pane, choose Report Wizard.
In the Name box, type Product Report.
Click Add.
Database Programming Using Access 2007 & Visual Studio 2008
[83]
You will see the following figure.
Click Next
Database Programming Using Access 2007 & Visual Studio 2008
[84]
You will see the following figure.
Click Next
Database Programming Using Access 2007 & Visual Studio 2008
[85]
You will see the following figure.
Click Next
Database Programming Using Access 2007 & Visual Studio 2008
[86]
In the Available fields pane, select all fields (press Shift key and select with your mouse).
Click Details> button.
Database Programming Using Access 2007 & Visual Studio 2008
[87]
Your report wizard should looks as follows.
Click Finish.
Database Programming Using Access 2007 & Visual Studio 2008
[88]
You will see the following figure.
Click Finish
Database Programming Using Access 2007 & Visual Studio 2008
[89]
Your completed report looks as follows.
Database Programming Using Access 2007 & Visual Studio 2008
[90]
5.3 Creating Microsoft Report Viewer
Project Add Windows Form.
In the Name box, type ProductReportForm and click Add.
Enlarge the form as follows.
In the Toolbox, look for Reporting and double-click MicrosoftReportViewer.
Enlarge the ReportViewer as needed.
Open the smart tags panel of the ReportViewer control, by clicking the triangle on the top right corner of the
control. In the Choose Report drop-down list, select ProductReport.rdlc .
Database Programming Using Access 2007 & Visual Studio 2008
[91]
Test your report form.
Your report should display as follows.
To format Price field into currency.
Right-click the cell (the oval shape) and then click Properties.
Select the Format tab and click the browse (…) button to open the Choose Format dialog box
Database Programming Using Access 2007 & Visual Studio 2008
[92]
In the Format box, select Standard, select Currency, and then select a currency format.
Click OK, and then click OK again to close the Textbox Properties dialog box