You are on page 1of 56

Visual Basic

Programming

1
Chapter
Database Management
9

2
Introduction

▪ Basic database terminology


▪ Fundamental database concepts
▪ Use ADO .NET to access databases
▪ Display, sort, and update database data
▪ Use the DataGridView control

3
Database
Management Systems

Visual Basic applications use database


management systems to make large
amounts of data available to programs
4
Visual Basic and Database
Management Systems
• Businesses must maintain huge amounts of data
• A database management system (DBMS) is the typical
solution to the data needs of business
• Designed to store, retrieve, & manipulate data
• Visual Basic can communicate with a DBMS
• Tells DBMS what data to retrieve or manipulate

5
Layered Approach to Using a
DBMS
• Applications that work with a DBMS
use a layered approach
• VB application is topmost layer
• VB sends instructions to next layer, the
DBMS
• DBMS works directly with data
• Programmer need not understand
the physical structure of the data
• Just need to know how to interact with
the database

6
Visual Basic Supports Many
DBMS’s
• Visual Basic can interact with many DBMS’s
• Microsoft SQL Server
• Oracle
• DB2
• MySQL

7
Database Concepts

A database is a collection of one or


more tables, each containing data
related to a particular topic
8
Terminology
• Database: a collection of interrelated tables
• Table: a logical grouping of related data
• A category of people, places, or things
• For example, employees or departments
• Organized into rows and columns
• Field: an individual piece of data pertaining to an
item, an employee name for instance
• Record: the complete data about a single item such
as all information about an employee
• A record is a row of a table

9
Database Table
• Each table has a primary key
• Uniquely identifies that row of the table
• Emp_Id is the primary key in this example
• Columns are also called fields or attributes
• Each column has a particular data type

Emp_Id First_Name Last_Name Department


001234 Ignacio Fleta Accounting
002000 Christian Martin Computer Support
Row 002122 Orville Gibson Human Resources
(Record) 003400 Ben Smith Accounting
003780 Allison Chong Computer Support

Column Field
10
VB and SQL Server Data Types
• VB data types must match table data types
• SQL Server and VB have similar data types

SQL Type Usage Visual Basic Type


Bit True/false values Boolean
DateTime Dates and times Date, DateTime
Decimal, Money Financial values Decimal
Float Real-number values Double
Int Integer values Integer
Smallint Integers -32,768 to 32,767 Short
Varchar(n) Variable length strings String
Text Strings more than 8000 char String
11
Choosing Column Names
• Define a column for each piece of data
• Allow plenty of space for text fields
• Avoid using spaces in column names
• For the members of an organization:
Column Name Type Remarks
Member_ID int Primary key
First_Name varchar(40)
Last_Name varchar(40)
Phone varchar(30)
Email varchar(50)
Date_Joined smalldatetime Date only, no time values
Meeings_Attended smallint
Officer Yes/No True/False values
12
Issues with Redundant Data
• Database design minimizes redundant data
• In the following employee table:
ID First_Name Last_Name Department
001234 Ignacio Fleta Accounting
002000 Christian Martin Computer Support
002122 Orville Gibson Human Resources
00300 Jose Ramirez Research & Devel
003400 Ben Smith Accounting
003780 Allison Chong Computer Support

• Same dept name appears multiple times


• Requires additional storage space
• Causes problems if misspelled
• What if a department needs to be renamed? 13
Eliminating Redundant Data
• Create a department table
Dept_ID Dept_Name Num_Employees
1 Human Resources 10
2 Accounting 5
3 Computer Support 30
4 Research & Development 15

• Reference department table in employee table


ID First_Name Last_Name Dept_ID
001234 Ignacio Fleta 2
002000 Christian Martin 3
002122 Orville Gibson 1
003000 Jose Ramirez 4
003400 Ben Smith 2
003780 Allison Chong 3
14
DataGridView Control

The DataGridView Control Allows you to


Display a Database Table in a Grid Which
Can be Used at Runtime to Sort and Edit
the Contents of the Table 15
Connecting VB to a Database
• VB provides tools to display database tables
• Data binding links tables to controls on forms
• Controls called components establish the link
• A wizard guides you through the process
• We’ll use these data-related components:
• Data source – usually a database
• Binding source – connects data bound controls to a
dataset
• Table adapter – uses SQL to select data
• Dataset – in-memory copy of data from tables

16
Connecting VB to a Database
• The flow of data from database to application

• Data travels from data source to application


• Application can view/change dataset contents
• Changes to dataset can be written back to the data
source

17
Data-Bound Controls

Some Controls Can Be Bound to a Dataset.


A Data-bound Control Can be Used to
Display and Edit the Contents of a
Particular Row and Column
18
Advantages of Data-Binding

◼ Can bind fields in a data source to controls:


◼ Text boxes

◼ Labels

◼ List boxes

◼ Contents of data-bound controls change


automatically when moving from row to row
◼ Data-bound control also allow the contents of a
database field to be changed

19
Sample Table – Cities Table

20
Sample Table – Countries Table

21
Megacities.accdb
▪ Contains the two tables Cities and
Countries shown earlier.
▪ This database will be used extensively in
the examples for this chapter.
▪ Several steps are required to bind to a
table of the database.

22
Binding to the Cities Table

Add a BindingSource control to the form.


(The control is in the Data and All Windows
Forms group of the Toolbox. It appears in
the form’s component tray with the name
BindingSource1.)

23
DataSource Property of
BindingSource1

click here

24
Choose Data Source Type

select

click on Next button

25
Choose Database Model

select

click on Next button

26
Choose Data Connection

click on New Connection button

27
Add Connection Dialog Box

click on Change button

28
Change Data Source Box

select

click on OK button

29
Add Connection Dialog Box

click on Browse button

30
Select Database File

double-click on Megacities.accdb

31
Add Connection Dialog Box

click on OK button
32
Choose Data Connection

click on Next button

33
click on Yes button

34
Save to File

check this box

click on Next button

35
Choose Database Objects

check on
Tables box

click on Finish
button

36
Changes in Properties Window
and Form

37
After Clicking on Data Member
Down-Arrow

click on Cities

38
VB Generated Items

new
new icon code

39
Binding Complete

• We are now bound to the Cities table via the


MegacitiesDataSet and the CitiesTableAdapter.
• The next four slides show how to bind an
additional table.

40
Connect an Additional Table
Add another BindingSource control to the form.

41
Set Data Source Property

click on MegacitiesDataSet

42
Set Data Member Property

click on Countries

43
VB Generated Items

new icon
additional code shows in Load event procedure
Me.CountriesTableAdapter.Fill(Me.MegacitiesDataSet.Countries)
44
Examples

45
Example 1: Form

txtTotalPop

46
Example 1: Code
Private Sub btnDisplay_Click(...) Handles _
btnDisplay.Click
Dim query1 = From city In
MegacitiesDataSet.Cities
Where city.country = "India"
Order By city.pop2010 Descending
Select city.name
lstOutput.DataSource = query1.ToList
lstOutput.SelectedItem = Nothing

47
Example 1: Code (continued)

Dim query2 = From city In _


MegacitiesDataSet.Cities
Where city.country = "India"
Select city.pop2010
txtTotalPop.Text = CStr(query2.Sum)
End Sub

48
Example 1: Output

49
Example 2: Form

txtName

dgvOutput

50
Example 2: Code

Dim query = From country In _


MegacitiesDataSet.Countries
Where country.name = txtName.Text
Select country.name, country.pop2010,
country.monetaryUnit
If query.Count = 1 Then
dgvOutput.DataSource = query.ToList
dgvOutput.CurrentCell = Nothing
Else
MessageBox.Show("Country not found")
End If 51
Example 2: Output

52
Example 3: Form

dgvOutput

53
Example 3: Code

Dim query = From city In _


MegacitiesDataSet.Cities
Let popIncrease = city.pop2015 - city.pop2010
Let formattedIncr =
FormatNumber(popIncrease, 1)
Where popIncrease > 1
Order By popIncrease Descending
Select city.name, formattedIncr

54
Example 3: Code (continued)

dgvOutput.DataSource = query.ToList
dgvOutput.CurrentCell = Nothing
dgvOutput.Columns("name").HeaderText = "City"
dgvOutput.Columns("formattedIncr").HeaderText
= "Population Increase"

55
Example 3: Output

56

You might also like