Chapter 8 Databases
Chapter 8 Databases
DATABASES
Chapter Objectives
Learners should be able to:
. describe the file based approach database system
. outline features of a Database Management System (DBMS)
. describe features of relational database which address limitations ofa file based approach
. explain different database views
. write SQL commands
. access data in a database through a high level language
. design database applications using entity relationship diagrams (ERDs)
o convert ERDs to relational databases schema in standard normal form
. normalise database tables up to second normal form
Introduction
Before the advent of computers, a manual 6le system was used to maintain records and files. All the
data was stored in separate files. But this system was good only for small organisations having small
number of items. The manual file system was also labour intensive, time consuming and inefficient.
To overcome these disadvantages and to make the processing fast, traditional filc processing system
was introduced. The 6le processing system had also its drawbacks such as data duplication. Generally,
traditional file processing systems were good in many cases in comparison to manual non computer
based system but still it had many disadvantages that were overcome by database management
sy6tem.
Example I
To illustrate traditional file database system, let us take an example ofa school where a student record
for an examination is stored in another file, his library record is stored in a different file and his
registration record is again stored in a di-fferent file that creates many duplicate values like Student
Number and Name.
335
)
Fig 8.1 Traditional file based d.atabase system
for a school
Example 2
consider a traditional banking system which
uses the file-based system in managing
data in the picture below. As we can see, the organisation,s
there are different departments in the banh
has its own applications which manage each of them
and ;il;;;;fferent
data 61.;. F;;;;;ng
system,
the programs can be the one to debit
credit i i"a tr,. oJ*1..r- ;""";;
mortgage loan or generate monthly statements ""
etc
"i-r"r, add a new
Persolael
Dep artmerr
tt
.{ccou!r Deplmrear
@
Loal Deprrmrelr
@F
@@
Fig 8.2 Tratlitional fle based database system
for a banking system
336
)
l-
. It is very difficult to maintain the file processing system.
. Any change in one file affects all the files which creates burden on the programmer.
' Data files and application programs are created by different programmers ofvarious depart-
ments.
* Dati Inconsistency
. Inconsistency in data format,
. Data inconsistency may arise since different copies ofthe same data are kept in diferent de-
partments. The data in these departments may be conflicting.
* Data Isolation
. It is diftcult for a new application to retrieve the appropriate data which might be stored in
various files that belong to other departments.
' Since files may be in different formats, writing new application programs to retrieve the ap-
propriate data is dificult.
* Security Problems
There are constraints regarding accessing privileges.
Application is added to the system in the ad-hoc manner so it is difficult to enforce those
constraints.
Database Approach
. The limitations ofthe traditional file based database system prompted the development ofthe
database approach as a new approach in managing large amount of organisationil informa-
tion.
337
Jr-d
f
I
il
l..tx ll,|]t
Database
' A database is a single organised collection ofstructured and related data, stored with minimum
duplication of data items so as to provide
. Databases can be accessed usingiitrerent
consistent *a .orrt.ou.l a"i" *,ir"l"
Jg*o",r"".
application sottware.
' Data stored in databases can be-accessed
by afl system users, but with diferent access
rights.
' Database operations may include addition of r.. .".o.d., deletion ,^"-i.a records,
338
"r
amendments to existing records, creation of relationships between files, searching a record
and removal or addition of fields.
t
File
t
Record
t
Field
I
i( Byte
T-
Bit
Fig 8.4 Buikling block of a database
* Bit
A single binary digit, for example,0 or l A bit is the smallest unit of storage in the computer
system.
* Byte
A collection ofbits usually 8 bits representing a character, for example, 10000001.
* Field
A collection of bpes describing an entity, for example, Name, Sex, ProductlD.
A field is also called an attribute. i1
In a relational database, a field is represented by the column'
* Record
A collection of related fields describing an entity, for example, patient record.
A record is also known as a tuple.
In a relational database, a record is represented by the row.
339
)
1 File
. A collection ofrelated records, for example,
customers file.
. In a relationat database, a fle is represent"j
Ufii. tuUf".
* Database
' ffH:Tffi::1fiffi:';j"'**ole a school database with teacher fi.Ie, student file, supptier
. Data Integritl
Data integrity means the correctness
of the data in the database. In other words,
the database is reliable and consistent the data available in
data.
. Data Security
Data security refers to the fact that
only authorised users can access the data.
enforced by usernames and passwora, Data security can be
ur". -a nglr".
f.irif"S.
Features of Database Management
System
Data Dictionary Management
The Data Dictionary is wh-ere the DBMS
stores definitions of the data elements
(metadata). The DBMS uses this and their relationships
function ,o roJ ofiir."r.quired data component
relationships. when programs access structures and
data in a database they are basically going
The Data Dictionary is often hidden from through the DBMs.
Programmers.
the ;;;il]. used by Database Administrators and
340
)
Data Transformation and Presentation
The DBMS can use the data transformation and presentation function to determine the difference
between logical and physical data formats. This function exists to change any data enteretl into required
data structures.
Security Management
Security management sets rules that determine specific users that are allowed to access the database.
These function restraints on what specific data any user can see or manage.
Transaction Management
A transaction is a unit of program that updates various data items. This refers to how a DBMS must
supply a method that will guarantee that all the updates in a given transaction are made or not made.
All transaction must follow the ACID properties.
341
This property ensures
that eirl all the operations ofa
Let's take an example transaction..fl..t in database or nonc.
of6"16ll tY"tm to understand
of $400 and Accounr B h..
$7t8
this'supp6s.4..;;;;;;;";-
'a transferring
lhis is a transaction is rransrerrins
rs
This ,r.,
transartin. that has
two oPerations
$l00to Account B.
$r00to Bb baran;;#; "^^19.-1..ount.A a) Debiting
oPttution passed successfrrlly
$r00f.";;i;;;ce b) creatins
A's balance would be while second failed, in this
ilt B would be having $700instead
$roo*t---le casc
in a banking system. "rsi-oo.
riiJu
troperry ensures that either the transaction
"ri".llJ,*n
Hi:":::y
of theoPeration rri"rri pr".l;#iftff shorrl.l r.;r r^.i+L^..a
should fail ,-
without executing any
Lonststency "irr #action
Relational Databases
A relational database is a collection
ofnormalised
vr uurruauseo retations
relations with distinct names
to link the relations. allowing users
A relation is a table with columns
and rows.
A table is a collection of records
It only applies to losical structure
stored urr"g
-rr, *a column structure.
a",iU"r", ,i",-.f,linrr,." structure.
Each column ..pr"i=.nt, "fO.
.E acn row represents
-attribute
a tuple or record.
or field
tach attribute has a distinct
name.
Degree is the number of
attributes in a relation.
Cardinality is the number of
tupt., in
Each cell ofrelation contains "..i"ti*
exactly one atomic (single)
value.
v.u
no jupri."t. iupi\qr,Er!.,
Each tuple is distinct; there are
342
)
. Order ofattributes and tuples has no significance.
' Relational databases have replaced hierarchical databases and network databases because
they are easier to implement and administer.
-j ;:".*
- ,t
rr/+
/
, Descriprion . euanrny
PlimarY KeY AttribYte/field
'' Each record, has a unique identifier that makes it easy to locate data when a user needs to
access a record.
' Each user can view the same data set in the most appropriate way for their needs.
' Security control may also be implemented by moving sensitive attributes in a given relation
into a separate relation with its own authorization and access rights.
' Diferent tables from which information has to be linked and extracted can be easily
manipulated by operators.
. They are easy to design, implement and manage.
. Ensures structural independence by use of normalization.
. Ensures ad hoc query capability, for example, sel is easy with relational databases.
343
Relational Dahbase
. Simple kev Kevs
A simple key contins
a single attribute,
for example, customer_id.
. Composite kev
. Candidate kev
A candidate key is an'attribrrt.
lrnr <^+ ^r^__.r ,.
;fl;;i..l"{il;;:i:iiilliiilr'i.t!"i.f', euarines ror uniqueness
lhat oreach row,tupre A
rryi*qyq:;ril:;h:L:,,'"1ilff
:*T:lll#;:;;lHix::kff;,ff
illi.Io",
**:#*#$,'"g;,ilg#;;il.';rjpt'-s?.:ffi i:il::,:*,il:;"..',,
.
primary kev
It is a candidatek.y
thut i,
contain a p.rimafie]. rrom a reration. Every
rsphvsicarv impremented. ff*#tli,f'"ffi',:ff.,;:;::^..o...1 reration must
"*: For exampre,
" il;'#; I::,'.'.f.*i::1":T *:;ru:,;gr,;.p"";
o ,^..-..
j.l:r+ k:y/Referencing key
;":,:il',:i?,.;l?;::t,;lf.ff i:TT.,:.Tf.:ffJ:*r:*,:*elheprimarvkevnerdfrom
*,;:*I1nTr.**ffi fi Ifl :*,."rerer",""rft H"iiiliil1:i#:*i'i::nr,*;
. Alternate kev
A candidate column
in a rel th"t haspotential to be
a prtmary key in
that ..luu"lttT- r
reration, ir,*'si"a.,,_t#J,l;l:'"Til:i:;:lfl:T;3:;.Tfl#I::ooll,ll:il,|f;'d:,:;1"ff;
.Secondary kev
A field used to identify
mor" than one record
at a time, for example,
a surname,
S.".-l",ic key/Natural
- ^:_ key
n^ semantic key is a key for wh
.or exampre, a semantic o:*ible values have ar
o..u,,.n."d.,.,iffi:ffi,ffi'{,i.';ili,i::i?$tit*,:f,,#$;.#il',1:T":H:ffi,'T:il:
"r,;lll-llt
344
.
Technical key/Surrogate key/Artificial key
A technical key is a key for which the possible values have no obvious meaning to the user or the
data.
These are used instead of semantic keys when none ofthe existing attributes c-an be used
to guarantee
uniqueness. In this case adding an attribute whose value is generated by the system may be the only
way to provide a unique value, for example, an oRDER_ID or INVOICE_ID value,12345'has no
meaning to the user as it conveys nothing about the entity to which it relates.
345 /
. Data Consistencv
;1ffi*!:*T::fff:lT:lTi.",T:ig::H,'jlf::onprogramsandthesvstemdata
jilffi Achange
*anot.i,iJ .";;ilr:fr:"".j"*:#i:";,:,,fl l;li l::;,.::*ig#.?,y,:
;HT::Tll j:;:Tf :*:Hi#j:ili,.i'"*;l:l{..i,*u,..-;:;;;;i-.uuo,,p.o,,u_
.'vst'rcuuus nave ro be made in the
has to be rewritten. data, then the ap-plicat,on
progr.m
. Improves Securitv
from unauthorised access.-only
*if;Wrliil:.:fl:.$glata authorised users must have
preventingu,.,,r,om,l*i'.ti-it:T:ff
;:,":,'tS:{:.ni**.;":."1}:i:Xl*,:
arternative J."'.;.;,";"Hes
;:f?:trTJ":r_,:H,:j#.: and passwords can be u,Jd ,o p,o,..,
*, u. "..Ji",;"#::.ffi';rf:T."tyr during updatingd";;;;;.;yi il",i"ra","u",.
Backup and Recovery
In a traditional fiJe processing
system, a user needs to back
time that wastes rots of time up the database after a regular
aid'rer"";..;. il;;;;;."Ji., tr,i. p-ur.-
interval of
of taking ba-Jup again and
;:::.*1i#:1ilL"J1ftt"*"r ';ii;';J.,1i1,.,n .",. orhardware aird software rairure.
,' *r,'.r, i*"t*;;:il#.Li1;:';*Xl3l'.",;.'.:;[",r'. osili:;;i#lills orthe state
Search Capability
lnere are nturerous queries ur mar ask about the data' Search
produce di;J;;;;'sers
^- -
speed of the database must
be fast to
ir'. a","tirl.
346
r''-
.
Concurrency Control
If two users are accessing data simultaneously and they both want to update values
ofthe same record,
then it may create concurrency. The DBMS has the power to control ;ncurrency
so that users trying
to update the same data do so in a controlled mannei and no transactions are lost
and the result of the
update is correct.
' StandardsEnforcement
As DBMS have central control of database so a Database Administrator (DBA)
can ensure that all the
applications follow some standards such as format ofdata. These standards heip
in data migrations or
in interchanging the data.
. Simplicity
Simplicity means to rePresent the overall logical view of data in a simple and clear manner.
The DBMS
is very simple for its users who use it. All the operations like insert, ielete,
create and update are very
simple to implement.
. Data Atomicity
An atomic.unit is any complete transaction in database. If any transaction is partially
completed, then
it rolls backs them. It is the duty of the DBMS to store a complete transactioi in database.
.
Data Migration
Data migration means storing data according to its popularity. In a database, some
data is accessed
frequently and at the same time some data ii accessed occasionally. So the DBMS store
frequently
accessed data in a manner that it can be accessed quickly.
.
Powerfrrl User Language
A DBMS permits end users to use database without having special training or expertise.
Any untrained
user can easily query search and uPdate data in the database. The user ian easily generate
report or
documents with less knowledge.
.
Provides Multiple Views of Data
A view may be a subset ofthe database. Various users may have different views ofthe database
itself,
for example, the bank teller has his view ofthe database diferent from that ofthe bank
manager who
can view the whole database. Users may not need to be aware ofhow and where
the data they refer to
is stored.
* Complexity
' A DBMS fi.rlfill lots of requirement and it solves many problems related to database. But all
these functionality has made DBMS extremely complex ioftware.
' DeveloPer, designer, DBA and end user of database must have complete skills if they want to
user it properly to avoid loss of data or database failure.
347
* TechnicalstaftRequirement
A team of technical staf such as the database developer, database designer
and database
administrator is required who understand DBMS and thJ organization
has i'o p"y larg" s"r"rie,
to them too.
* Size
' As DBMS becomes big software due to its functionalities so it requires lots of space and
memory to run its application eficiently.
. As more data is fed in it so the size ofthe database increases.
348
_T
Activity I
l ' In piitsfinit out the benefits and problems of computet batsed database systems as compared to
manual fiIing systems.
A Database Environment
' The database environment is a collection of components that control the collection,
manage-
ment and use ofdata.
. A database environment is made up of the following components:
L hardware
II. software
III. data
IV. procedures
V people
ZDrr)
Hardware Software Procedures People
Bridge
Machine Human
Fig 8.6 Database Enyironment Components
* Hardware
' Hardware can range from a personal computer to a network of computers where the database
is run.
* Software
The software includes DBMS software, operating system, network software (if necessary)
and
also the application programs.
r Data
Includes data used by the organisation and a description of this data called the schema.
The data in the database is persistent, integrated, stiuctured, and shared.
* Procedures
Rules and instructions that should be applied to the design and use ofthe database and DBMS.
The procedure may contain information on how to log on to the DBMS, how to recover
the
database etc.
* People
These include the database designer, database developer, database administrator, application
programmer and end users who operate the database.
349
Roles of a Database Administrator (DBA)
.
Setting up and creating.the database
together with the programmers.
.
Maintains the data dictionar y.
y::::::*3erfor1a31e oithe database to see if any problem wilt surface.
.'[::#::',f
'fi::i""j:::t;:'ll*d:j{;;;.i#;J;,T'##i;,rorexamp,e,ir
.. *:,,:::::"r:'_T1l
Train users :{ 1 o-i':i"'
naa'J""g.i;; #'u*"i ;ji.:::'jJl
on how to use the database.
Implement error identification and correction
routines.
. Ensuring that the database meets the
needs oith. o.g*irutiorr.
. Control, manage and maintain the database.
. Define, implement and control database
storase.
. Ensure that policies and procedures
are estabh'Jed.
. Guarantee effective production, control
and or. ofa"r".
. Define the strategy of backup storage
and recove;;;;_ system breakdown.
. Supervise amendments to the dataiase.
. Ensures that the data is secure from
unauthorised access.
. Controls the database environment.
. Standardise the use ofdatabase and
associated software.
. Support the development and maintenance
ofa"tub"r. upptication proiects.
' Ensure all documentation rerated
to standard, *Ji-pt.*.ntation is up-to-date.
' Liaison with the management on what
suitabr" h".i*"r. und .oftware to purchase
in order
to implement the database.
* Data Dictionary
' The database dictionary contains
names and descriptions ofevery data
element in the database.
' Descriptions are on how a". .i.-."ir
*" ;d;il.each other. The Data Dictionary (DD)
stores data in a consistent memory,
reducing data redundancy.
* Data Languages
' A special language used to describe the
characteristics ofa data element placed
into the Data
Dictionary. This language is called the
Data D.C.riU* f,"r,g*ge (DDL).
* Security Software
' Provides toors used to protect the database
from unauthorised access.
* Recovery and Archiving System
. These allow data to be copied onto
backups in case ofdisaster.
* Report Writers
' These are programs used to design
output reports without writing an algorithm
in any
programming language.
* TeleprocessingMonitors
' software that manages communication
between the database and remote terminars.
350
Database Views and Schemas
* Viewe
' A view refers to how a user sees data stored in a database. Each user has his/her
own view of
data, for example, a standard database user can be restricted from seeing (viewing)
sensitive
data that only managers can view.
. Thus, these two have different views ofthe database.
' Contents ofa view are defined as a query on one or more base relations
and the view does not
necessarily actually exist in the database but is produced upon request,
at time ofrequest.
Advantages of Views
' Views are dynamic' meaning that changes made to base relations that affect view attributes are
immediately reflected in the view.
' Provides powerful and flexible security mechanism by hiding parts of database from certain
users.
' Permits users to access data in a customised way, so that same data can be seen
by different
users in dilferent ways, at same time.
. Can simplify complex operations on base relations.
. A user's view is immune to changes made in other views.
. Users should not need to know physical database storage details.
* Schemas
It.refers to the- overall design of the database. It can be a collection of named
objects such as
tables, views, functions, packages, and other packages.
Schemas provide a logical classification ofobjects G the database.
A Sub-schema describe different views ofdatabase.
It consists of three levels namely external level, conceptual level and internal level.
351
User n
External
level I vi.*n I
Conceptual
level
lnterna
level
Physical data
organization
Database
352
Data Independence
o Data independence is the immunity of application programs
to changes in storage structures
and.access- techniques. For exampre, in iiaditionui
firJ processing
attribute, change index structure then, the applications are
,i""^, r *l add a new
affected.
' Thus, data independenge.renderl application programs
immune to changes in the rogical and
physical organisation ofdata in the system.
' It means that programs are isolated from changes in the way the
data are structured and stored.
Conceptual/internal
mapping ' - Physical data indepenclence
Database Languages
' Since a database supports a number ofuser groups, the DBMS
must have languages that
support each user group.
353
* Structured Query Language (SQL)
There is a differ'ence between SQL and MySQL.
SQL is a programming language that is used to communicate and manipulate a database.
MySQL is a popular relational database management system (RDBMS) developed by Oracle
that has SQL built in it.
SQL commands consist of Englishlike statements which are used to query, insert, update, and
delete data in a database.
Since SQL commands resemble English language sentences in their construction and use they
are therefore easy to learn and understand.
SQL is referred to as non-procedural database language, which means that, when we want to
retrieve data from the database it is enough to tell SQL what data to be retrieved, rather than
how to retrieve it.
SQL uses a set of commands to manipulate data in database.
SQL commands are dMded into four subgroups namely Data Definition Language (DDL),
Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control
Language (TCL).
SQL
corirrnandg
I
I I
DDL OML lCL
(:REAIF SELE(:] (I()i.rt tIr
3s4
-\^ - --\
DBMS Interfaces
Tlpes of interfaces provided by the DBMS include:
b. Forms-Basedlnterfaces
. Displays a form to each user.
. User can fill out form to insert new data or fill out only certain entries.
' Designed and programmed for naiVe users as interfaces to canned transactions.
c. (Graphical User Interfaces
. Displays a sc\ema to the user in diagram form.
355
. The user can speciry a query by manipulating the diagram.
. GUIs use both forms and menus.
Database Security
Database security refers to methods ofkeeping data in a database safe from various hazards and
from unauthorised access.
Activity 2
l. In pairs, research and trite down the functions of the follo$ing ilatabase personnel:
a) Database designer
h) Database developet
c) Application programmer
d) End user
2. Write notes on the two main types of Data Manipulation Langrages (DMLs) namely:
* high-levelhonprocedural
* Ior+-le,vellprocedutal.
356
/
Basic SQL Commands
*
Create a database
.A relational database is made up ofa collection of related tables. So the first thing is to create a
database which will then contains one or more tables (relations).
.To create an SQL database, the create database statement is used.
.The syntax is given below:
CREATE DATABASE databasename;
Example:
CREATE DATABASE Entertainment; I
. To check whether the database is created you can write the SQL command:
SHOWDATABASES;
* Delete a database
. The drop database statement is used to delete an existing SQL database.
. Deleting a database will result in loss of complete information stored in the database.
Example:
DROP DATABASE Entertainment;
called "Last-Name" is to be used to hold names, then that particular column should have a
"varchar" (variable-length character) data rype. a.' )
357
a SQL Constraints
corstraints refer tocertain properties that data in a database must comply with and
are used
to limit the type of data that can go into a table.
' Thus, a constraint is a rule associated with a column that the data entered
into that column
must follow.
' Constraints enforce limits to the data or tlpe of data that can be inserted/updated/deleted
from a table.
The whole purpose ofconstraints is to maintain data integrity when such operations
as updat-
ing/deletion/insertion are being performed on data in a table.
This ensures the accuracy and reliability of the data in the table.
Ifthere is any violation between the constraint and the data action, the action is aborted.
constraints can be column level or table level. column level constraints apply to a column,
and table level constraints apply to the whole table.
Constraints are used to limit the type ofdata that can go into a table.
The following table shows constraints commonly used in SeL:
Constraint DescriDtion
NOTNULL Ensures that a column cannot have a NULL value, for example, p.ir""ry
key must not be left blank "
UNIQUE Ensures that all values in a column are different, for .x"-ple, p.i-".y k y
field must have unique values. "
PRIMARY KEY Uniquely identifies each row in a table. The primary key must satisfr the
NOT NULL and UNIQUE constraint.
FOREIGN KEY Uniquely identifies a rodrecord in anothe! table
DEFAULT Sets a default value
for a column when no value is specified
INDEX Used to create and retrieve data from the databale very quickly
. lhe syntax ot the table if you were to use optional constraints is grven
CREATE TABTE'rablename'
("columnl " "dara rype'
Iconstraint],
"column2" "data rype"
Iconstraint],
"column3'"data type"
Iconstraint]);
Note: You may have as many columns as you'd like, and the constraints are optional.
Example:
CREATE TAILE Employee
(lD int NOT NULL UNTQUE
First_name varcha(l 5) NOT NUtL
t
Last_name varchad20) t{OT NUtL
Age number(3)NOT NULI
City varchar(20) DEFAU[T'MUTARI',
PRIMARY KEY (ID));
358
In the example above' First-name, Last-name, Age and City will be the name of the fields or columns
of the Employeet table. Different constraints have been set for different columns of the Employee
table, for example, the NOT NULL, UNIQUE and PRIMARY KEy constraints have been
set on the
'ID'column.
Example:
CREATE TABLE Customer AS
SELECT First_N4 me, Last_Name, Age, City
FROMEmpbyee;
. In the abov,e example, SQL creates a new table called "customer" (which is a copy of the
"Employed' table).
(FtRsT_ctrLUMN,..,LAST coLUMN)
Example:
INSERT INTO EMPLEYEE
(FIRST-NAME, LAST-NAME, AGE, GITY)
VATUES (.AsHELy', .MaNvERUKE', I 6, .MurARE');
' In the example above, Ashely' will be inserted into the First-Name column, followed by
'Manyerukd into the Last-Name column, followed by 16 into the Age column and 'Mutare'
into the City column.
. It is imPortant to note that if you are adding values for all the columns of the table, there is
no need to specifr the column names in the sQL query. However, make sure the order of the
values is in the same order as the columns in the table.
. The syntax is as follows:
INSERT INTO TaBLE-NAME
VALUES (vaLUEt, vaLUEz, vaLUEg, ,..);
Example:
INSERT INTO EMPLoYEE
VALIJES (.wayNE', .MaNvERUKE', I B, .HaRARE,);
. The values will be added in the table columns in the order they are given.
Activity j
1. Write SQL commands to
a) Create a table called *Employee" to enter details of employees in an organisation. The table must
contain the folloting information about your employees: employee_no, firstname,lastname, title,
age, d4rafiment and salary. Salary must have 2 decimal places.
b) Enter the following recotd in the "Employed' table
8001, Ryan,Magaya, Dr, 45, Accounk,4500,00
Hint: set employee-no as the Primary key. All the fields must contain data. Set appropriate data
types and sizes for your fields
360
, straint information.
. The syntax is as follows:
Example:
DROP TABLE Employee
. To delete thi data inside a table and leave the table as it is use the truncate table statement'
. The syntax is as follows:
TRT NCATE TABLE tablename
Example:
TRIJNCATE TABLE EmPloYee
* Deleting data in a database table
. The delete statement is used to delete records or rows from the table'
The WHERE.clause contains the condition which specifes which record(s) should be deleted.
If you leave the WHERE clause all records in the table will be deleted'
The whe.e clause is also used in update or select statements when modiffing or searching
data in tables.
Example:
DELETE FROM EmPloYee
WHERE CitY = 'Mutard;
. In the above example, all records that contains 'Mutare' in the city column will be deleted.
Example:
DELETEFROM EmPloYee
WHERE City = 'Mutare Or First-Name = 'Munashe';
. 'Munashe' in
In the above example, all records that contains 'Mutare in the City column or
the First-Name field will be deleted.
Example:
DELETE FROM EmPloYee
WHER.E First-Name = 'Cecilia' and Age = 30;
. In the above example, all records that contains 'Cecilia' in the First-Name column and 30 in
Age column will be deleted.
Example:
DELETE FROM EmPloYee;
. In the above example, all records in the Employee table will be deleted' '
361
* euery data in a database table
' In most cases users ofa database perform
search operations to find specific
data from a
based on specific conditions- Foi
example;;-;;;ug., ,,,,"y want to display records database
employees who earn $750.00 and ofall those
below.
. The data returned is stored in a result
table called the result_set.
' The select statement is used to query
the d;;;" and retrieve serected data that match
criteria that is specified. the
. The syntax of the select statement
is given below:
Example:
SELECT First_Name, Lasr_Name,
Ciry
FROM Students
WHERE City = 'Masvingo;
Example:
SELECT First-Name, Last-Name, City
FROM Students
WHERE First-Name Like A%';
. Will display first name, last name and city from Students table for all records with first names
that starts with ?t and ends with any character(s).
Example:
SELECT First-Name, Last-Name, City
FROM Students
WHER.E City Like'-a%';
Will display first name, last name and city from Students table for all records with city that
starts with any single character followed by'a and any character(s).
Example:
SELECT First_Name, Age, City
FROM Teachers
WHERE Age > 40;
. Will display first name, age and city from Teachers table for all records with age greater than
40.
Example:
SELECT First-Name, CitY
FROM Teachers
WHERE City <> 'Harard;
. Will display fust name and city from Teachers table for all records with city that does not
include 'Harare',
c) SQL Operators
The where clause can be combined with AND, OR, and NOT operators tofilter records based
on more than one condition.
The AND operator displays a record if all the conditions separated by AND is TRUE.
363
. The OR operator displays a record if any of the conditions separated by OR is TRUE.
. The NOT operator displays a record if the condition(s) is NOT TRUE.
Exarnple:
SELECT Name, Title, Hobby, City
FROM Patrons
WHERE Title ='Mr' AND Hobby ='g[6s5''
. Will display name, title, hobby and city from Patrons table for all records whose title matches
'Mr' and hobby matches 'Chess'. Only the records that satisff both conditions will be displayed.
Example:
SELECT Name, Title, Hobby, City
FROMPatrons
WIIEREName = 'Makanaka' ORCity = 'Gweru';
. Will display name, title, hobby and city from Patrons table for all records whose name matches
'Makanaka' or city matches 'Gweru'. Only the records that satisfr one or both of the conditions
will be displayed.
Example:
SELECT't
FROM Patrons
WHERENOT City = 'Harare';
. WiU display all records and columns that matches any city that excludes 'Harare'. Al1 records
with city that is not 'Harard will be displayed.
Activity 4
I. the following SQL queria will display:
Explain what
a) SELECT *
FROMI Patrons
WHERE Title ='Mrs' AND (Hobby ='Swimmiry! OR City ='Bulavalo';
I
FROM Cttstomers
WHERENOT Name ='Trish'AND Age <= 25;
.l) SELECT Name, Surname, Age
FROM Customers
WHERE Surname LIKE'- a';
---- ,l
I
,l
364
The update statement is used to update or change existing records in a table that match a spec-
ified criteria.
The syntax of the update statement is given below:
UPDATE tablename
SET columnl = valuel, column2 = value2,...
WHEREcondition
Example:
UPDATE Patrons
SET Title = 'Profi Hobby = 'Rugbyi Age = age + l, City = .11ur".0
WHERE Name = 'Ryan';
. The above sQL statement updates the title to 'prof', hobby to 'Rugby', age to age plus l and
city to 'Harard where the Patron's name is 'Ryanl
. If the age in the age column was 35 the age will be set to 36 (35 + l).
Example:
UPDATE Patrons
SET Hobby = 'Rugbyl City = 'Harard - i.
' In the above SQL statement all the records are going to be updated to 'Rugby' and 'Harard in
the hobby and city columns respectively since the where clause has been left.
. So be carefirl when you omit the where clause.
. The where clause also determines how many records will be updated.
Example:
UPDATE Patrons
SET Hobby = 'Netball'
WHERE City = 'Mutare';
. The following SQL statement will update the hobby to 'Netball' foi all records where city is
'Mutarel
Activity 5
A relation named contains the alttibutes:
36s
Relational Database Modeling
' The main objective of.relational data analysis
is to organise all of the data items used by the
system into a set of well normalised relations.
' This is done to eliminate unnecessary duplication (redundancy)
of data items in different
relations, and ensures.data accuracy andrntegrity (the
possibility of probrems arising when we
modifr, insert or delete data _ usua'lly referrj to a,
d"iab"se
"no_ai"r).
*. Database Entity Relationship Diagrams (ERDc)
' An entity relationshiP diagram is a diagrammatic way of
representing the relationships between
the entities in a database.
' An ERD defines entities, their attributes, and show the relationships
between the entities.
' ERDs are created during conceptuar database design
and during iogical a"tuuur. design; the
ERDs are converted into relational data models.
Uses of ERDs
.
To illustrate the logical structure ofa database.
.
To sketch out the design ofa database.
a. Entity
. An entity is an object or concept about which data
is to be held, for example, place, person,
event etc.
An entity is named using single_ nouns, for example, students,
courses, employers etc.
A specific example ofan entity is called an instance.
Each instance of an entity becomes a record or a row
in a table. For example, the customer
Praise Mungazi is a record in a table called customer.
An entity is represented by a rectangle.
i) Strong Entity
AJtrong entity is one whose existence does not depend
on the existence of any other entity in
a scnema-
It is denoted by a single rectangle.
A strong entity always has the primary key in the set ofattributes
indicating that each entity in
a strong entity set can be uniquely identified.
The relationship between two strong entities is denoted
by a single diamond.
u) Weak Entity
A weak entity is an entity that depends on the existence
of its owner entity, i.e. stronger entity.
For example, the order item entity depends on the existence
rht";;;;rtity.
A weak entity does not have a prjmaryley instead it "f
has a partial key that unilueiy aiscriminates
the weak entities.
The primary key of a weak entity. is a composite key
formed from the primary key of the strong
entity and partial key ofthe weak entity.
The relationship between a strong entity and a weak
entity is denoted by a doubre diamond.
366
/
Loan
stro.g.l.,tity I
Weak entity
. In the ER_diagram above, for
each loan, there should
loan would no1 u. mtJ tte at least one borrower otherwise
. The customer entity does
in Loan enuty set. that
not depend on a loan entitv
borrow any loan it rl'JJu. even if a customer does
. urt.d in customer enu*;.,ltt"utt
oth:r.lhing to note is that
not
lhepartial
the
a weakei;.ril;ji;: primary key. So the Loan_name,
key of the weak
t y "rr"* ffi-'' er1;o,;;
wcaK entit/ ;il;",;:",::::-:i" oi.ur-tori,;;:"",r;;;:Lr,-",,
and cust-ID prim*v k.y "
. To identifr who had borrowed a given loan can
be don t with the help
weak entity (Loan-n"m.l curtJo). of primary key of the
b. Attribute
Composite Attribute
.'
composite attributes are specific
attributes for other attributes.
For example, the attributeihaar"*,,.-
attributes are called comfosite
l-"u.";:;illi tes number, street and
attributes. city. These
367
Multivalued Attribute
A multivalued attribute is an attribute that can have more than one value.
This is diferent from an attribute having its own attributes.
For example, a learner entity can have multiple subject values.
358
/
Circle
Area I
Radius
c. Relationship
'"-t.iJ,t'""titp -:-.:^- L-+.rapn Fniities.
entities' It shows how two entities share
is a link or association between
"*"tabresin*l1l'^:T::-:i:"i:'"i:;11:["n,1ff;:n*
f ?:rTfiiilt'01ffi :fi iit L"g 'p'"nt; otle may have any number of
relationship where an ott*tl# "t -o'
o" tht'-uny'or thild'table' ' ' back the primarv kev on
the
^"*;#.:;;t"'
ro achieve this, the thild t"bli;;lt;;;
itiit *r'itrt [nk
kty, and the parent table is
,i. table are known u. " foi.ign
t'J#;il.;;;le"
narent table. These 6elds ", "friia oe viewpoint of th:.:hild)'
our' ir"-
'*i't
*itt'-""t:mfm:tl3;::'ffi:"f:
it is possible for a rccord """il:;;;;.;;!i"-t"
possible for an entrv on
;ifili;;;;iit should not be
as rererentiar
to be managed bv rures known
;:*i:t'*f:ffi:,'5jff::lll}|.1ips on
f,'-*iiq"':ledif the foreign kevdoes not exist
Hi.t;T;:ff',-:"i:JJl"itlt["o'*#iT"irl, *htitht ent-ry on'the parent table
is
the oarent table, or *i' d"of "i.fttfa"t"bl.,
example' teaches is the
are described by verbs' for
;trt"# f^ttii"!,"- "t"tio"ships
and learner'
,-.i"tiorrtttip U.t*ein teacher diamond shape'
ai.i",,"tritp tr action is represented by a
Learner
Teacher
i) *'"n.
.1":;'iff'l::iffi :flriswhenthe'"-':"'Yl*:'::::,T:i$#::i:;""::'f
i"'"tt"' i* supervise other teachers and
can
. This creates ttlf-linktd
" "ilffi't;;:t;;;;
also be suPervised' ,t
:1
I
369
i
Teacher
Supervisioi
Tlpes ofRelationships
. There are 3 types of relationships in relational
database design namely:
a.One-to-One
b. One-to-Many (or Many-to-One)
c. Many-to-Many
d. The Crow's Foot Relationship Symbols
are used to represent relationships.
Employeeld
FirstName
LastName P"yld
Payld HourlyRate
370
/
Learner Fills
Teacher Office
Crtyld
Customerild
CityName
FirstName
LastName
Cityld
Examples:
An inspector supervises many schools, but each school has only one insPector,
Inspector School
One professor can teach many courses, but one course can only be taught by one professor,
371
)
Course
Professor
Many-to-Many Relationship (M:M)
Each entity instance in one entity class is related to
multiple entity instances in another entity
class; and vice versa-
In other words, a row in table A can have many matching rows in
table B, and vice versa.
i: difficult to represent many-to-many relationslhips in a database, a many_ ,o_,o*y
9:1" i,
(M:M) relationship is decomposed into two one-to-many
ir:M) relationships.
To decompose a many-to-mrly relationship into iwo one_to_many relationships
an
intermediary table or ')unction table" or 'reference table" is used
to lirrt tt . t*o t"bt.,-,o-jon",.
The intermediary table must have two fields that reference the
primary key ofeach ofthJother
two tables.
Examples:
A ticket holder may attend a number ofconcert performances, and each concert may be attended by
many ticket holders.
372
Ticket_holder Concert
attends
Many-to-Many relationships are not encouraged in E-R diagrams since they violate the 3NF
ofdatabases.
I
To remove M-N relationships, a link entity is used to link entities,
Another entity called ticket is created to decompose the many-to-many relationship
There is a one-to-many relationship between a ticket holder and a ticket (each ticket holder
may have several tickets, but each ticket will be held by onty one person)
There is also a one-to-many relationship between .orr...t ani a ticket (each concert may
" concert)
have several tickets, but each ticket will belong to one
One-to-One
One-to-Many
Many-to-Many
373
V. Complete the diagram
' connect all the entities with lines, and add
diamonds to describe each relationship until
all
relationships have been described.
' Some entities may not have any relationships
while others may have multiple relationships.
Hint: i)Removeredundanl
ii..provide r;ffi?T."Ifr :;:TlT*%l.iliil*o'i,l,,rute,
" and rerationship in
the diagram.
iii. Use singular nouns in naming entities.
iv. Never connect a relationship io another
relationship.
Example
ABC Bus comp.ny owns a number ofbuses.
Each bus is allocated to a particular route,
routes may have several busses. Each route passes although some
through a number of towns. one or more drivers
are allocated to each stage ofa route, which
corresponarlT ioo.rr.y through some or all
on a route' some ofthe towns have a garage ofthe towns
wh..i bur., are" kept and each ofthe buses are identified
by the registration number at a ."n cir.yiir...nt
,ro.t.r, ofpassengers, ,i"." ,lr" ,.ila.s vary in
size.and can be single or double-decked.
iach rout. ir ia."iin.a uy a route number and information
available on the average number of pur..r,g".. is
p..i"y ro, .u"r, D;]";;;r;'*
-"1"-
""r.i.dn'umber.
number, name, address, and sometimes aielephone
"-ploy".
a. Entities
. Bus
. Route
. Town
. Driver
. Stage
. Routes
. Garage
b. Relationships
. A bus is allocated to a route and a route may have
several buses.
. Bus-route (m:l) is serviced by
. A route comprises ofone or more stages.
. route-stage (l:m) comprises
. One or more drivers are allocated to each stage.
. driver-stage (m:l) is allocated
374
A stage passes through some or all of the towns on a route.
stage-town (m:n) passes-through
A route passes through some or all of the towns
route-town (m:n) passes-through
Some ofthe towns have a garage
garage-town (l: I ) is situated
A garage keeps buses and each bus has one 'home'garage
garage-bus (m: I ) is garaged
c. Attributes
. Bus (reg_no, make, size, deck, no_pass)
. Route (route_no, av_pass)
. Driver (emp-no,name, address,tel_no)
. Town (name)
. Stage (stage number)
. Garage (name, address)
Hint: Underlined attributes are key attributes/key fields
E-A-R Diagram
Activity 6
I. Create an entity relationship diagram for the following scenario:
a) A cinema shows many films and a film is shown at many cinemas.
b) Each student can take many classes, and each class can be taken by many students.
Converting ERDs to Relational Databases Schema in Standard Normal Form
The ER diagram rePresents the conceptual level of database design while the relational schema is the
logical level for the database design.
When converting ER diagram to relational schema it is important to take note of the following:
a. Speciff schema of relation itself.
b. For an entity-set E with attributes al, a2, ...,an create a relational schema with same name E,
and same aftributes al, a2, .. ,, an.
375
c. Specifi primary key on the relation.
d. Primary key of relational schema is same as primary key of entity_set.
e. Specifr any foreign key references to other relations.
Personld
Phone
Take the multi-valued attribute and turn it into a new entity or table ofits own. Then make
a l:N relationship between the new entity and the existing one, that is, create a table for the
attribute and add the primary (id) column of the parent entity as a foreign key within the
new table as shown below:
376
/
Person(Igsen.id , name, lastname, email )
Phone( ghgnsid , personid, phone )
. Personid within the table Phone is a foreign key referring to the personid ofperson.
377
one can place the primary key of the car within the table of the person which we call in this
case foreign key as shown below:
Person(Ielse4:is! , name, lastname, phone, email , canegno )
Car( carregno , name )
The other method is to put the personid as a foreign key within the car table as shown be-
low:
Person( pgfsegi(L, name, lastname, email )
Car( carregno , name , personid)
For situations when the Person does not have a car, that is, has no carregno, the attribute can
set to NULL
378
/
. To rePresent such relationship, the personid as the Parent table must be placed within the
Child table as a foreign key but not the other way around.
r Many-to-Many(N:N)Relationships
For instance, the Person can live or work in many countries. Also, a country can have many people,
379
To express this relationship within a relational schema we use a separate table as shown be-
low:
job(ltlelevel)
employee(ernployee id. employee_name)
branch(bfaush_&aqe, branch_ciry assets)
works_on(einployee id. branch name. title)
Example
380
customer(cust id, name, street-address, city)
loan(loan id. amount)
borrower(eust id. loan id)
Activity 7
Map the following EAR diagram into a relational schema:
38r
adress
Anomalies in DBMS
' Database anomalies are faults or weaknesses in a database as a result ofpoor planning and
storing everything in a flat database.
. Database anomalies are usually removed by normalisation.
' There are three types of anomalies that occur when tie database is
not normalised. These are
insertion anomaly, update anomaly and deletion anomaly.
. Let's take an example to understand this.
Example
' suppose a manufacturing co-mpany stores the employee details in a table named
employee that
has four attributes: emp-id for storing employee's id, emp_name for storing
employeet name,
emp-address for storing employeet address and emp_dept for storing the
iepaiment details
in Which the employee
emnlovee wnrkc Af some
works. At cntnp h^i61 of +i-- the
^f time l^Lr^ looks
+t - table
like rL:-
r^^r-^ r:r-- this:
emp_id emp_n.rme emp_ad&ess emp_dept
101 Bolgani Mutare D001
101 Bongani Mutare D002
-
123 Abdul Bulawayo D890
166 Glenn Harare D900
166 Glenn Harare D004
382
' The above table is not normarised. we
wilr see the problems that we face when a tabre
is not
normalised.
a. Update Anomaly
In the above table we have two rows for employee
Bongani as he belongs to two departments
ofthe company.
If we have to update the address of Bongani, then
we have to update the same in two rows or
the data will become inconsistent.
If somehow, the correct address gcts updated in one
department but not in other then Bongani
would be having two diferent which is
data. "ddr"rr.., ""i.;;:;;;;;;fi;;;"';'.'""#:,"r,
b. Insert Anomaly
' An insertion anomaly is-a failure to place information
about a new database entry into all the
places in the database where info.-utio'
about that new entry needs to be stored.
' In a normalised database, information about a new
entry n.id* to be inserted into only one
place in the database.
' In an inadequately normalised database, information
about a new entry mayneed to be inserted
into more than one place' and, some of the needed
addition"l t;r"ttil;;"y b] mirsed.
' Suppose a new employee joins the company, who
is under training anJ.*rJ.rity no,
we would not be able to insert the data int tn. "rrigrr.a
::ila*i#ffT.then tutt" ii-.,_p_deptield
c. Delete Anomaly
' A deletion anomaly is a failure to remove information about an existing database entry when
it is time to remove that entry.
' In a ProPerly normalised database, information about
an old, to-be-gotten-rid-ofentry needs
to be deleted from only one place in the database.
' In.an in-adequately normalised database, information
about that old entry may need to be
deleted from more than one place, and, some of th"
' "..d;;lli.i""Ji"i.u."r;rbe
suppose, if at one time the company croses the department missed.
Dg90 then deleting ihe rows that
are having emp-dept as D890 would also delete
th^e information
is assigned only to this department. "r"*pr.y.. fuiul since she
' To overcome these anomalies, the data in the database
need to be qormalised.
Database Normalisation
' Normalisation is a process oforganising the data in a database
to avoid data redundancy,
insertion anomaly, update anomaly and deletion anomaly.
383
e'
Normalisation provides indexing which speeds up the access ofdata and also increasing up-
dating and deleting performance.
f. Normalization breaks the database into smaller tables making it much easier for database
administrators to provide security control to the different tables.
Focus will be on the first normal form and second normal form only.
Example
. A table is created to store student data which will have student's roll no., their name and the
name ofsubjects they have opted for as shown below.
But out of the 3 students in our table, 2 have opted for more than I subject. And we have
stored the subject names in a single column. But as per the lst normal form each column must
contain atomic value.
In order to solve this, we have to break the values into atomic values. The table below is now
the updated table that now satisfies the First Normal Form.
384
roll no Name Subject
l0I Tkrfadzwa OS
l0l Tafadzwa CN
103 Munashe Iava
l02 David C
t02 David VB
' By doing so, although a few values are getting repeated but values for the subject column are
now atomic for each record/row.
' Using the First Normal Form, data redundancy increases, as there will be many columns with
same data in multiple rows but each row as a whole will be unique.
, 2NF only applies to tables with composite primary keys (more than one primary key).
. Therefore, any relation having a key with a single attribute is in Second Iiormal'Form.
Example
. Let's have a table called Student, to store student infonnation as shown below.
Let's have another table Score, to store the marks obtained by students in.the different sub-
jects. We will also store name of the teacher who teaches that subiect along with.marks.
38s
score_id student id
I
lQq.ua Marks Teacher
IO I 70 Java Teacher
2 l0 2 75 C++ Teacher
3 ll 3 80 VB.Net Teacher
. In the score table we are saving the studenr_id
to know which studentt marks are these
subject id to know for which ,uUi".t and
tt . _".t *.
fo..
' It is not possible to get marks for a student
usrng student_id only because we
dont know for
which subject.
' possible to use the subjectjd to get the marks because we don't know
i,il.1lrhHnot for
. Hence we need student_id + subjectjd
to uniquely identifi any row. Together,
student id +
subject-id forms a candidate Key for this
t"ur.] *rii.r, .- f#;;ru";";;;.' "
Partial Dependency
' In the Score table, we have a corumn named
teacher which is only dependent
for Java itt Java Teacher and for c++ on the subject,
it, cii r.Jii", ro, vB.Net
' As mentioned earlier, the.primary -a
key ro. tttir tuul. i. a composition
its vB.Net Teacher.
student-id and subject-id but ttt. t.""tt"rt'u-.-o-nry of two columns which is
id, and has nothing to do with student_ij.
d.p.rdr;;;;ii..i, rr"#im subjecr_
' This is partiar dependency, when
for a-c-omposite primary key, any attribute
in the table depends
only on a part of the primary key
-a o" ifr.'"o_pfete primary key.
"ot
How to remove partial Dependency
' To remove partial dependency' we can divide the table, remove the attribute which is causing
yarlial^dependency, and move it to ,o,,,. ott..iubt..,'t ere
it fits well.
' In the score table, the sorution ir to..-ou..otoni' teacher frominscore tabre and add it to the
Subject table.
. The Subject table will appear as shown below:
Example
. Let's look at the unormalised Sales table
below
386
/
i
SalesStaff table
SalesStaff table
Customer table
CustomerlD EmployeelD Branch CustomerName
s00r 103 Z^ka GMB
s002 103 Zaka ZESA
s003 104 Bindura ZINARA
s004 104 Bindura DMB
s005 104 Bindura NRZ
s005 105 Chipinge csc
Second Normal Form
. To decide whether our table is in 2NF let us look at the following issues:
I. The SalesStafftable has one column (Branch) which is not dependent on the EmployeelD. The
Branch column does not help in any way to describe yho the employee is.
II. There are several attributes which do not completely rely on the entire Customer table primary
key' For a given customer, it does not make sense that you should have to know both the
CustomerlD and EmployeelD to find the Customer. You need only to kn6w the CustomerlD.
387
I
' Therefore, the columns that are not completely dependent
on the fu primary key in both
cases are moved to new tables.
' In the case of Branch, a Branchofice was created. A foreign key (BranchlD)
was then added
to salesstafftable so we can still describe in which branch sal"i p"rron
i is based.
BranchOffice table
BranchID Branch
B0l Zaka
B,02 Bindura
B03 Chipinge
SalesStafftable
Customer table
CustomerlD Branch CustomerName
s00l Zaka GMB
s002 Zaka ZESA
s003 Bindura ZINARA'
s0M Bindura DMB
s005 Bindura NRZ
s006 Chipinge CSC
Now lett create a table named salesStaffcustomer with two columns customerlD and
EmployeelD to describe which customers a sales person calls upon.
Together, they form a primary key. Separately, they are foreign keys to the
customer and
SalesStaff table respectively.
SalesStaffCustomer table
388
CustomerlD EmployeelD
s001 I03
s002 103
s003 104
s004 104
s005 104
s006 t05
. with thesechangesmade the dataffi, isshownbelow
Customer
CustomerlD
Branch
CustomerName
SalesStaffCustomer
CustomerlD (FK)
EmployeelD (FK)
SalesStaff
EmployeelD
SalesRepresentative
BranchlD (FK)
BranchOffice
BranchlD
Branch
Actit'ity 8
I' A school uants to store the data of teachers and the subjects they teach, They create a table
shown belou.
teacher_id Subject teacher_age
lll Maths 38
ltl Physics 38
222 Computer Science 38
333 Physics 40
333 Chemistry 40
389 /
i
o) in lNF or not. Give a reason.
State whether the table is
b) (i) Explain why the table is not in 2NF.
(ii) Illustrate how to normalise the table into 2NF.
thd
I ;
'_ hbhlcol! 0arg;lnterprirqSidmr0atrbrxiAaer2,lii].MicrosoftAccttt
t1
.' ho'ri (rralt ftrmlDlti Drtibrlrlo0lr orbtlRd
: Prtn.nt-fiilhbh
tfuol-tih
I ctir{rm,lur
390
oo llindc$,!Applicltion1 - t",ti<rcsoft ViJU.l Studio
Fih Edrt Vicw Proj.ct Build O.brjg T.rm O.ta Toolr fuchttadura
Format tart Ah!ty!!
iio;i-e{ d - ':4-
, - 6ILI
' =
r- Prym.nt Fil.
' Click Project menu when you are using vB.Net 2013 or crick Data menu
when using vB.Net
2010. Then select and click Add New Data Source as shown
below:
Microsoft Visual Basic.Net 2013
39r
11 irrihdc!v!Appta<rti6nl . l,1i.rcjcft Vir!!l Studic
F'k tdil Vi.w p.oJ.ct Butd O.bug Tc.n For6d -foob Archh.ctuE Tcst A..ty:.
-J show Drt. sourEcr shtft- Att- o
I
Add N.w D.t Sosrc....
,I
F'IFEI
Tr.nr.ct-sQl Ed'tor
ht' y.":;;"a r"-. a.t.;; .-ia .r"J"* t,l anili* lr.il.d r", F;; ji,prr.a;.n.
392
DBt. 5curcc icnfigur.ticn llrir!rd X
I
Th. drt.b.t. modcl you choot! dltcrmin.r th? typ* of drtr objcctl jouirppliiation ccdc us.5. A dltr3dtil. wi b..ddcd to
your proj.ct.
I
I
There is need to browse and locate the correct database, in our case, the database is Davev
Enterprise_System. Therefore, click New Connection.
+ Ccnn.d'cn n.ing
393
Add fc hnecticn X
Data 50urcc:
t-_-
Parsword: I I
[ Srve my password
Advanced.,.
fl viacos
'j- Lo<.1Dirk (Cr)
R.covcry (Dr)
-
HP-TOOLS (t'
-
E N!t'\,ork
Click on Test Connection to test whether the database was connected successful.
394
Entcr inlorrn.tion tc conn.ct to th. s.l.ct.d d!t. tout<. o. click
''Ch.nq. to choosc . dificr.nt d.t. 5cu.c. .nd /or p.ovid...
Dtt. sourcc:
' t't;c,oroft n...,s Databa:c Filc {OLE DB} ; Ch.ng....
T.n Cohh.ction
+ Connaction irinq
< Pr.\,,ioui
395
Choo'. Your D.tr CoFnaGidon
,
Wbkh 6tr (ollncctbn thoutd you..pp&.tton ul5? to (orBr.ct to ihc d.t b.rc?
D.vry_Enierprir._Syn.m..c.db
Ncw Conocction...
Conhaclion
Th! conncdionyou rclcct.d ui.5 r lo<.ldrt. tilG th.r ir not in the
cuncnt projcc!. Would you likcto copytht fil.to your proj.ct.nd
modify thc <onn.<tion?
Ityou copy th. d.i. ril.to yolr proj.<t it vri bc (opied io thr proj.ct.5
odpd dir.<to.y ..ch ti . you run th. .ppticltion. pr.$ Fl lo; '
irtorm.tion on controlling this bchrvior,
lo.".y-r.i.if'r,._sy't.-c """..tio"it,-s I
<P'.Yiour t.-j:-f
Click to select Tables and Views.
If need be, one may change the Dataset name, however, the default name is mostly recom-
mended.
Click Finish
396
Dtt. Scu.<. Contiqur.tion Wiz.rd
rxl
Choor Your O.t br'. ObJ.ct
DaaSa namc
l!r"V_Entcnrisr_SVstcmOaeSa-
J
' click viedother windows/Data s-ource if you are using Microsoft Msuar sasic.Net 2;t3
h:l'*.:ffiillfi iii:T:.- irvou are i',in! r'lr..;n visuar BasicNe;;;il;. p,.,,
. Select the colrect data source ifyou
have more than one data sources,
' the table you want to rink with ruri.to.ort
viruJ iasic.Net, in this case serect payment_
Fiick
oo tJindowrApplicrtionl - Mi(.osott Visurt studic
Filc Edit vilw proj.ct B! d D.bug T.rm Drt! Toolr Ar.hitcctur. T.rt
i."r_!rit-,ddt,,, - ilr : ;! Show Oatr Source
An bac Window Hclp
' click the down arrow on payment_File as shown below and crick Details
397
Drta Sourccs Prymcnt Filc.vb [Ocignl' .
I.Id'
J la-l-r C
w :}'t D.v!r-
J Clicrt_Filc
H"
DltrGridl4lw
DdrilE
lNoncl
Customire...
.u Amount-P.id
click and drag the icon to the left of the Payment_File name as shown below. Drag and releasc
the icon on the form and all the fields from the payment_File table will be sho*rr1t on"..
The other method is to click and drag each field from the paymenr_File separately and placc
it on the form.
Paym.nt Filc.vb lDcsignl* x
,-, rl5 9i '.t
,{ Davcy_
tr PrFncnt Fh
J Clicnt-Filc
,! Prymcnt_File - ll ( 0 ot{o} | }l ',r Xd
LOt Rrf_No o-- '.. .,
:9HBr-: i
i.bl Anrount_P!id a-- ---
iqg!ry,.
t'.--.- '-.. ,
i.U'l..l|F, :
If you are using Microsft visual Basic.Net 2013 when one clicks the details option, the icon
immed.iately to the left of Payment-File changes from 9f dlla
Drag and drop that icon on the respective form. In this case, the payment_File form
Adjust textboxes and labels as required by dragging and resizing them as shown below.
398
/
i
.:r Prymrnt Filc .. |.,EI
l< { c ct{o} , il ;XiJ
Rol llor
Clea lD:
llunc:
Sumadrcl
Ou.r{fy: II
il
tH Pnc.:
Anourt P.id: t.
. Run the system, the data in the database is then displayed on the vb.net form.
r
'l " XrJ
t ol2
Lffi*,__l
cl..r lD:
lelr l
-
lo.'.y l
It-'"E - I
ttt-
{i-
li---
I
-I r
Click the Move Next icon and Move Previous to view the next record or previous record
respectively, if any.
t
'-l
I
399
L1 l
i19 I
400