DDM Print Out
DDM Print Out
Aim:
Problem Definition
Information plays a vital role in the development and growth of every organization. Currently, the various
departments manage student information independently in their own ways. There are no common, standardized
process and program for capturing, processing and storing student‟s information. This has kept student information
disintegrated in different departments and information provided to the various departments by the students is
characterized with discrepancies. The problems facing the current manual system are data redundancy, difficult to
update and maintain, inconsistent data, insecurity, difficult to impose constraints on various data file and difficult to
backup.
The process of collecting and analyzing information about the part of the organization that is to be
supported by the database system, and using this information to identify the requirements for the new
system.
Relations in Student
a description of the data used or generated;
the details of how data is to be used or generated;
Syntax
column1 datatype,
datatype,
....
);
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer, date, etc.).
Example:
PersonID int,
LastName varchar(255),
FirstName varchar(255),
varchar(255)
);
TABLE table_name
Example
ALTER TABLE Customers ADD
Email varchar(255);
To change the data type of a column in a table, use the following syntax:
DateOfBirth date;
Date:
Aim:
Introduction:
The ER model defines the conceptual view of a database. It works around real-world entities and the
associations among them. At view level, the ER model is considered a good option for designing
databases.
Notations in ER Model
Example:
Normalization:
Exmaples:
14 John 7272826385, UP
9064738238
14 John 7272826385 UP
14 John 9064738238 UP
1. EMP_ID EMP_NAME
2. EMP_ID EMP_PHONE
3. EMP_ID EMP_STATE
A relation is in third normal form if it holds atleast one of the following conditions for every
non-trivial function dependency X → Y.
1. X is a super key.
2. Y is a prime attribute, i.e., each element of Y is part of some candidate key.
Example:
EMPLOYEE_DETAIL table:
201010 UP Noida
02228 US Boston
60007 US Chicago
06389 UK Norwich
462007 MP Bhopal
Example: Let's assume there is a company where employees work in more than one department.
EMPLOYEE table:
1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
EMP_COUNTRY table:
EMP_ID EMP_COUNTRY
264 India
EMP_DEPT table:
EMP_DEPT_MAPPING table:
EMP_ID EMP_DEPT
D394 283
D394 300
D283 232
D283 549
Functional dependencies:
1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
Candidate keys:
For the first table: EMP_ID
For the second table: EMP_DEPT
For the third table: {EMP_ID, EMP_DEPT}
Now, this is in BCNF because left side part of both the functional dependencies is a key.
Result:
EX.NO:03 Implement the database using SQL Data definition with
constraints, Views
Date:
Aim:
Procedure:
DDL COMMANDS
SQL> create table stud (sname varchar2(30), sid varchar2(10), sage number(2), sarea
varchar2(20));
Table created. SQL>
desc stud; Name
Null? Type
2.Constraints
Integrity constraints: Integrity constraints guard against the accidental damage to the database.
● Null
● NOT Null
● Primary key
● Unique key
● Foreign key
● Check constraints
● Default constraints
DESCRIPTION:
a) NULL: Null value is a member of all domains and as a result is a legal value for every
attributes.
Column of any data type may contain null value unless the column was defined as not null when
the table was created.
b) NOT NULL : Not null specification prohibits the insertion of null value for this attributes.
c) PRIMARY KEY:
A primary key is a one or more columns in a table used to uniquely identify each row in
a table. It uniquely identifies the attribute value.
d) UNIQUE KEY: unique key is used to ensure that the information in the column for each
record is unique.
CREATE TABLE Orders ( OrderID int NOT NULL PRIMARY KEY, OrderNumber int
NOT NULL, PersonID int FOREIGN KEY REFERENCES Persons(PersonID));
f) CHECK CONSTRAINTS :Check clause is to ensure the attribute value satisfy specified
condition.
3. VIEWS
Definition
▪ A view is a SQL query that is permanently stored in the database and assigned a name.
▪ A view is a virtual table in the database whose contents are defined by a query.
▪ A view does not exist in the database as a stored set of data values.
▪ A view can be used to restrict a user‟s access to only selected rows of a table called as
Horizontal Views.
▪ A view can be used to restrict a user‟s access to only certain columns of a table called as
Vertical Views
To create a VIEW
Syntax
CREATE VIEW view_name AS SELECT column1, column2, ...FROM table_name
WHERE condition;
Dropping a VIEW
Syntax
Result:
EX.No:4
Query the Database using SQL Manipulation
Date:
AIM :
PROCEDURE:
Creating a Table:
▪ CREATE command is used to create a new table in the database.
▪ CREATE command has two formats
● Create an empty table.
SYNTAX:CREATE TABLE table-name (field_name datatype);
CREATE TABLE Persons ( PersonID int, LastName varchar(255),
FirstName varchar(255), Address varchar(255), City varchar(255));
Modifying a Table:
▪ ALTER command is used to modify the structure of a table in the database.
▪ ALTER command can be used in Two modes.
● ADD: To add one or more columns.
● MODIFY: To modify one or more fields defined in the table
SYNTAX:ALTER TABLE table-name ADD/MODIFY (field_name datatype);
ALTER TABLE Persons ADD Email varchar(255);
Deleting a Table:
DROP command is used to remove the structure and data of a table from the database.
SYNTAX:DROP TABLE table-name;
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
INSERT command:
To insert new values into a table in the database.
● INSERT INTO table-name VALUES (value1, value2…);
● INSERT INTO table-name (column1, column2...) VALUES (value1, value2...);
UPDATE command
To modify or update an existing row or rows of a table in the database.
SYNTAX:UPDATE table-name SET column=value WHERE condition;
DELETE command:
To delete an already existing row or rows from a table.
SYNTAX:DELETE FROM table-name WHERE condition;
Truncating a Table:
TRUNCATE command will delete the data from the table but the table structure will
remain intact.
SYNTAX: TRUNCATE TABLE table-name;
TRUNCATE TABLE Categories;
INSERT command:
To insert new values into a table in the database.
❖ INSERT INTO table-name VALUES (value1, value2…);
❖ INSERT INTO table-name (column1, column2...) VALUES (value1, value2...);
UPDATE command
To modify or update an existing row or rows of a table in the database.
SYNTAX:UPDATE table-name SET column=value WHERE condition;\
UPDATE Customers SET ContactName = 'Alfred Schmidt', City= 'Frankfurt' WHERE
CustomerID = 1;
DELETE command:
To delete an already existing row or rows from a table.
SYNTAX:DELETE FROM table-name WHERE condition;
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
SQL INBUILT FUNCTION & SQL CLAUSES
⮚ Date Function
⮚ Numeric Function
⮚ Character Function
⮚ Conversion Function
⮚ Miscellaneous Function
Date Function
They operate on date values and produce outputs, which also belong to date data type except for
months, between, date function returns a number.
1. Add_month:This function returns a date after adding a specified date with specified number of
months.
NUMERIC FUNCTIONS
1. abs
Example: select abs(-25)from dual;
2. ceil
Example: select ceil(59.67) from dual; 3.exp
Example: select exp(6) from dual;
4. floor
Example: select floor(99.3)from dual;
5. power
Example :select power(15,2) from dual;
6. mod
Example: select mod(100,3) from dual;
7. round
Example: select round(100.3236,2) from dual;
8. truncate
Example: select trunc(100.256,2)from dual; 9.sqrt
Example: select sqrt(225)from dual;
CHARACTER FUNCTIONS
1. initcap(char)
Example: select initcap(„nandhini‟)from dual;
2. lower(char)
Example:select lower('NANDHINI')from dual;
3. uppe(char)
Example:select upper('nandhini')from dual;
4. ltrim(char,[set])
Example:select ltrim('cseit','cse')from dual;
5. rtrim(char,[set])
Example:select rtrim('cseit','it')from dual;
6. replace(char,search string,replace string);
Example:select replace('jack and jue','j','bl')from dual;
7. substr(char,m,n)
Example:select substr('information',3,4)from dual;
CONVERSION FUNCTION
1. to_char():This function converts date to a value of varchar type in a form specified by date
format. If format is negelected then it converts date to varchar2 in the default date format.
Syntax: to_char(d,[format]);
2. to_date():This function converts character to date data format specified in the form character.
Syntax: to_date(d,[format]);
Miscellaneous Functions
1. uid – This function returns the integer value (id) corresponding to the user currently logged in.
GROUP FUNCTIONS
1. avg
Example: select avg(total)from nandhinir;
2. max
Example: select max(percentage)from nandhinir;
3. min
Example: select min(marks)from nandhinir;
4.sum
Example: select sum(price)from nandhinir;
COUNT FUNCTION
SQL CLAUSES:
If you want to find rows that do not satisfy a condition, you can use the logical operator, NOT.
NOT results in the reverse of a condition. That is, if a condition is satisfied, then the row is not
returned.
For example: If you want to find out the names of the students who do not play football, the
query would be like:
SQL ORDER BY: The ORDER BY clause is used in a SELECT statement to sort results either
in ascending or descending order. Oracle sorts query results in ascending order by default.If you
want to sort the re cords in a descending order, you can use the DESC keyword
Syntax
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
● Having clause is used to filter data based on the group functions.This is similar to
WHERE condition but is used with group functions.
● Group functions cannot be used in WHERE Clause but can be used in HAVING clause
● The HAVING clause was added to SQL because the WHERE keyword could not be used
with aggregate functions.
SYNTAX:
SELECT column_name, aggregate_function(column_name) FROM table_name GROUP
BY column_nameHAVING aggregate_function(column_name) operator value
SQL ALIAS
● The LIKE operator is used to list all rows in a table whose column values match a
specified pattern.
● It is useful when you want to search rows to match a specific pattern, or when you do not
know the entire value. For this purpose we use a wildcard character '%'.
2. QUERY :select
firstname,lastname from student where firstname like'_a%';
SQL BETWEEN ... AND Operator
The operator BETWEEN and AND, are used to compare data for a range of values.
QUERY :select firstname,lastname, age from student where age between 10 and 15;
SQL IN Operator:
The IN operator is used when you want to compare a column with more than
one value. It is similar to an OR condition.
QUERY :select firstname, lastname, subject from student where subject in('maths','science');
NESTED SUBQUERIES:
IN:
Set of collection of values produced by a select clause.
Syntax: SELECT column_name(s)
FROM table_name WHERE column_name IN (value1, value2, ...);
SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');
NOT IN:
The not in connective tests for the absence of set membership.
Syntax:select att1,att2 from table1 where att1 not in(select att1 from table2);
EXIST:
The expression evaluates to true only if the sub example represented is not empty.
NOT EXISTS:
The expression evaluates to true only if thesubexample represented evaluates to
Syntax:select att1 from table1 where not exists (select * from table2 where
table2.att2=table1.att2);
SOME:
The some allows as to rewrite the queries in a form that resembles closely our
formulation of the example in English.
Syntax: select att1 from table1 where exist att2>some(select att2 from table1 where att1=value);
The > some comparison in the where clause of the outer select is true if the assets
value of the tuple is greater than one member of set of all asset values for branch.
ALL:
The construct >all corresponds to the phrase “greater than all”.
Syntax: select att1 from table1 group by att1 having sum(att2) >= all(select sum(att2) from
table2 group by att1.
DELETE:
A delete request is expressed in same way as a query. The delete operation is used to
delete all or specific rows from database. We cannot delete values of particular attribute.
Syntax: delete from relation where Condition;
Table Creation:
Table1:
create table book(bookid number(10),title varchar(20),pubyear number(10),unitprice
number(20),authornamevarchar(20),publishernamevarchar(20));
Table3:
create table order(orderno number(10),bookid number(10),orderdatedate,quantity
number(10),price number(10));
1. Display the
name of all books for which order is placed.
QUERY:select title from book wherebookid in(select bookid from order5);
9. Display the title of book that have price greater than atleast one book published in the year
2004.
QUERY:select title from book where price>some(select price from book where pub_yr=‟2004‟);
10. Display the title of book that have price greater than all the books published in the year
2004.
QUERY:select title from book where price>all
(select price from book where pubyear=‟2004‟);
Result:
EX.No: 5 Querying/Managing the database using SQL Programming
Date:
Aim:
PROCEDURE:
PL/SQL stands for Procedural Language extension of SQL.
PL/SQL is a combination of SQL along with the procedural features of programming languages.
It was developed by Oracle Corporation in the early 90‟s to enhance the capabilities of SQL.
Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL block. A
Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.
Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends
with END.
Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. Every
DECLARE
Variabledeclaration
BEGIN
ProgramExecution
EXCEPTION
Exceptionhandling
END;
In addition to SQL commands,PL/SQL can also process data usin flow of statements.the flow
of control statements are classified into the following categories.
BRANCHING in PL/SQL:
1. Simple IF
2. ELSIF
3. ELSE IF
SIMPLE IF:
Syntax:
IF condition THEN
statement1;
statement2;
END IF;
IF-THEN-ELSE STATEMENT:
Syntax:
IF condition THEN
statement1;
ELSE
statement2;
END IF;
ELSIF STATEMENTS:
Syntax:
IF condition1 THEN
statement1; ELSIF
condition2 THEN
statement2; ELSIF
condition3 THEN
statement3;
ELSE
statementn;
END IF;
NESTED IF :
Syntax:
IF condition THEN statement1;
ELSE
IF condition THEN statement2;
ELSE
statement3;
END IF; END
IF; ELSE
statement3;
END IF;
ITERATIONS IN PL/SQL
Sequence of statements can be executed any number of times using loop construct.
It is broadly classified into:
Simple Loop
For Loop
While Loop
SIMPLE LOOP
Syntax:
LOOP
stateme
nt1;
EXIT [ WHEN
Condition]; END
LOOP;
WHILE LOOP
Syntax
WHILE condition
LOOP statement1;
statement2;
END LOOP;
FOR LOOP
Syntax:
FOR counter IN [REVERSE] LowerBound..UpperBound
LOOP
statement1;
statement2; END
LOOP;
Exercise:1
write a pl/sql program to swap two numbers with out taking third variable
PROGRAM
set serveroutput on declare
a number(10);
b number(10); begin
a:=&a;
b:=&b;
dbms_output.put_line('THE PREV VALUES OF A AND B WERE'); dbms_output.put_line(a);
dbms_output.put_line(b);
a:=a+b;
b:=a-b;
a:=a-b;
dbms_output.put_line('THE VALUES OF A AND B ARE'); dbms_output.put_line(a);
dbms_output.put_line(b);
end
OUTPUT
Enter value for a:
10
Enter value for b:
20
old 5: a:=&a;
new 5: a:=10;
old 6: b:=&b;
new 6: b:=20;
THE PREV VALUES OF A AND B WERE 10
20
THE VALUES OF A AND B ARE 20
10
PL/SQL procedure successfully completed.
3. Write a pl/sql code block to calculate the area of a circle for a value of radius varying
from 3 to 6Store the radius and the corresponding values of calculated area in an empty
table named areas ,consisting of two columns radius & area
TABLE NAME:AREAS
create table areas50(radius number(10),area number(6,2));
4. write a pl/sql code block that will accept an account number from the user,check if
the users balance is less than minimum balance,only then deduct rs.100/- from the
balance.this process isfired on the acct table.
PROGRAM
set serveroutput on declare
mano number(5); mcb
number(6,2);
minibal constant number(7,2):=1000.00; fine
number(6,2):=100.00;
begin mano:=&mano;
select cur_bal into mcb from acct50 where acctno=mano; if
mcb<minibal then
update acct50 set cur_bal=cur_bal-fine where acctno=mano; end
if;
end;
b) PL/SQL FUNCTIONS
Function:
- Returns a value
- FUNCTION name RETURN data-type IS
Exercise 1:
Exec n1
Exercise 2:
Create a procedure which accepts two numbers and display its sum.
exec add_num(5,10);
Exercise 3:
Create a Procedure which accepts an empno and increments his salary by 1000.
create or replace procedure inc( a in number) is
begin
update emp50 set salary = salary+1000 where
eno = a;
end;
exec inc(45);
Function creation
Function created
old 4: a:=&a;
new 4: a:=21; grade
is d
c) TRIGGER
PROCEDURE:
⮚ Only use database triggers for centralized, global operations that should be fired for the
triggering statement, regardless of which user or application issues the statement.
⮚ Do not define triggers to duplicate or replace the functionality already built into the
oracle database. For example do not define trigger to implement integrity rules that can be done
by using declarative constraints.
⮚ The excessive use to triggers can result in complex interdependencies, which may be
difficult to maintain in large applications. Only use triggers when necessary, and beware of
recursive and cascading effects.
Elements in a Trigger:
o Trigger timing
o For table: BEFORE, AFTER
o For view: INSTEAD OF
o Trigger event: INSERT, UPDATE, OR DELETE
o Table name: On table, view
o Trigger Type: Row or statement
o When clause: Restricting condition
o Trigger body: PL/SQL block
“Before triggers” execute the trigger body before the triggering DML event on a table. These
are frequently used to determine whether that triggering statement should be allowed to
complete. This situation enables you to eliminate unnecessary processing of the triggering
statement and it eventual rollback in cases where an exception is raised in the triggering action.
“After triggers” are used when the triggering statement is to be completed before the triggering
action and to perform a different action on the same triggering statement if a BEFORE trigger is
already present.
“Instead of Triggers” are used to provide a transparent way of modifying views that cannot be
modified directly through SQL DML statements because the view is not inherently modifiable.
You can write INSERT, UPDATE, and DELETE statements against the view. The INSTEAD
OF trigger works invisibly in the background performing the action coded in the trigger body
directly on the underlying tables.
⮚ UPDATE
⮚ INSERT
⮚ DELETE
Trigger Components:
o Statement: The trigger body executes once for the triggering event. This is the default. A
statement trigger fires once, even if no rows are affected at all.
o Row: The trigger body executes once for each row affected by the triggering event. A
row trigger is not executed if the triggering event affects no rows.
Trigger Body: The trigger body is a PL/SQL block or a call to a procedure. Syntax:
CREATE [OR REPLACE] TRIGGER trigger_name
Timing Event1 [OR event2 OR event3] ON table_name Trigger_body
Exercise1:
PROGRAM:
set serveroutput on
create or replace trigger tri52 after insert on snt52 for each row
begin
dbms_output.put_line('record inserted'); end;
Trigger created.
PROGRAM
set serveroutput on
create or replace trigger trg50
after insert or update or delete on dept52 begin
dbms_output.put_line('Thank You');
end;
Trigger created
OUTPUT:
Thank you
1 row updated
Query:delete from dept52 where deptno=15;
EXERCISE 3:
set serveroutput on
create or replace trigger del52_tri
before delete on emp52
for each row
begin
insert into emp49 values(:old.empno,:old.ename,:old.job,:old.salary,:old.deptno);
end;
Trigger created
Query:delete from emp52 where empno=1; 3
rows deleted.
EXERCISE: 4
PROGRAM:
set serveroutput on
create or replace trigger etrig12 after update on emp12 for each row begin
if(:new.salary<:old.salary)then
raise_application_error(-20030,'increase the salary');
end if;
insert into updemp050 values(:new.salary,sysdate); end; /
OUTPUT:
Result:
EX.NO 6 Database design using Normalization – bottom-up approach
Date:
Aim:
Procedure:
Normalization
Exmaples
14 John 7272826385, UP
9064738238
EMPLOYEE table:
The decomposition of the EMPLOYEE table into 1NF has been shown below:
14 John 7272826385 UP
14 John 9064738238 UP
1. EMP_ID EMP_NAME
2. EMP_ID EMP_PHONE
3. EMP_ID EMP_STATE
● A relation will be in 3NF if it is in 2NF and not contain any transitive partial dependency.
● 3NF is used to reduce the data duplication. It is also used to achieve the data integrity.
● If there is no transitive dependency for non-prime attributes, then the relation must be in
third normal form.
A relation is in third normal form if it holds atleast one of the following conditions for every
non-trivial function dependency X → Y.
1. X is a super key.
2. Y is a prime attribute, i.e., each element of Y is part of some candidate key.
Example:
EMPLOYEE_DETAIL table:
EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY
EMPLOYEE_ZIP table:
EMP_ZIP EMP_STATE EMP_CITY
201010 UP Noida
02228 US Boston
60007 US Chicago
06389 UK Norwich
462007 MP Bhopal
Example: Let's assume there is a company where employees work in more than one department.
EMPLOYEE table:
1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
EMP_COUNTRY table:
EMP_ID EMP_COUNTRY
264 India
264 India
EMP_DEPT table:
EMP_DEPT_MAPPING table:
EMP_ID EMP_DEPT
D394 283
D394 300
D283 232
D283 549
Functional dependencies:
1. EMP_ID → EMP_COUNTRY
2. EMP_DEPT → {DEPT_TYPE, EMP_DEPT_NO}
Candidate keys:
For the first table: EMP_ID
For the second table: EMP_DEPT
For the third table: {EMP_ID, EMP_DEPT}
Now, this is in BCNF because left side part of both the functional dependencies is a key.
Output:
Thus the normalization is executed in the realation.
Result:
Ex.No 7 Develop database applications using IDE/RAD tools
Date:
Aim:
Procedure:
The above diagram shows the development environment with all the important points labeled.
Many of Visual basic functions work similar to Microsoft word eg the Tool Bar and the tool box
is similar to other products on the market which work off a single click then drag the
width of the object required. The Tool Box contains the control you placed on the form window.
All of the controls that appear on the Tool Box controls on the above picture never runs out of
controls as soon as you place one on the form another awaits you on the Tool Box ready to be
placed as needed.
The Project explorer window gives you a tree-structured view of all the files inserted into the
application. You can expand these and collapse branches of the views to get more or less detail
(Project explorer). The project explorer window displays forms, modules or other separators
which are supported by the visual basic like class'es and Advanced Modules. If you want to
select a form on its own simply double click on the project explorer window for a more detailed
look. And it will display it where the Default form is located.
Properties Window
Some programmers prefer the Categorisized view of the properties window. By defaulting, the
properties window displays its properties alphabetically (with the exception of the name value)
when you click on the categorized button the window changes to left picture.
When we start Visual Basic, we are provided with a VB project. A VB project is a collection of
the following modules and files.
1. The global module( that contains declaration and procedures)
2. The form module(that contains the graphic elements of the VB application along
with the instruction )
3. The general module (that generally contains general-purpose instructions not
pertaining to anything graphic on-screen)
4. The class module(that contains the defining characteristics of a class, including its
properties and methods)
5. The resource files(that allows you to collect all of the texts and bitmaps for an
application in one place)
It also includes a Toolbox that consists of all the controls essential for developing a VB
Application. Controls are tools such as boxes, buttons, labels and other objects draw on a form to
get input or display output. They also add visual appeal.
You may have noticed that when you click on different controls the Properties Window
changes slightly this is due to different controls having different functions. Therefore more
options are needed for example if you had a picture then you want to show an image. But if you
wanted to open a internet connection you would have to fill in the remote host and other such
settings. When you use the command () you will find that a new set of properties come up the
following will provide a description and a property.
Microsoft have included some freebies with visual basic to show its capabilities and functions.
Dismantling or modifying these sample projects is a good way to understand what is happening at
runtime. These files can be located at your default directory /SAMPLES/
To Open these projects choose 'Open Project' from the 'File' menu. Then Double click on the
samples folder to open the directory then Double click on any project to load it.
Opening a new visual basic file & Inserting Source code.
From looking at the examples it time to make your own application. Choose 'New Project' from
the 'File' menu. Use the blank form1 to design a simple interface for an estate agents database,
have some textboxes for names and other details. Insert some controls and make it look
professional. Textboxes can be used to store there name and other details, make sure you put a
picture box in for a picture of the house.
Now insert the following source code for your application.
In this example the project has been loaded and the maillist.frm has been selected for viewing. This Ms
Mail example project useds 6 forms and 1 modules.
In Design mode, when the form is viewed, the code attached to any screen object may be inspected by
double clicking on that object. The screen shots below show the interface of the Ms Mail example
(.../samples/Comtool/VBMail/MaiLLST.FRM) to view the code for this form select from the project
window item.
Database Object
The first thing you must do in your application is to open a database where your tables are
stored. You need to declare a variable to hold your database in order to do this. This is done
with:
This gives you a variable/object that can hold a reference to your database. To open a simple Access
database named "MyDatabase.mdb", do this:
So, now you have opened a database. This won't give you any data. What you need to do is open
a table in the database. You're not limited to open a single table; sometimes you have two or
more tables that are related to each other and linked together w ith foreign keys, and there are
ways to handle this to. But in this "Visual Basic - Database Primer”
RecordSet Object
Visual Basic uses an object called RecordSet to hold your table. To declare such an object and to
open the table, do this:
Declared a RecordSet object and used the Database object's OpenRecordSet method to open a
table of type Dynaset. Open a RecordSet in several modes. VB's online help file explains the
different modes and what they are for. The Dynaset mode is the mode I use mostly. It gives you
a RecordSet that you can add, delete and modify records in.
Accessing records
Now that we have opened a table (referred to as RecordSet from now on) we want to access the
records in it. The RecordSet object allows us to move in it by using the methods MoveFirst,
MoveNext, MovePrevious, MoveLast (among others). I will use some of these to fill up a list
box with the records of our RecordSet.
To get this example to work, make a database (with Access) called "MyDatabase.mdb" with the
table "MyTable" in it. This table should have the fields "ID" of type "Counter" that you set to be
the primary key, the field "Name" of type Text and a field "P hone" of type Text. Add some
records to it. Put a list box on a form and call it "lstRecords".
Private Sub Form_Load()
Set dbMyDB = OpenDatabase("MyDatabase.mdb")
Set rsMyRS = dbMyDB.OpenRecordSet("MyTable", dbOpenDynaset)
This will make the list box fill up with your records when the form loads. The line that says If
Not rsMyRS.EOF Then rsMyRS.M oveFirst tells the program to move to the first record in case
there are any records at all. The EOF is a Boolean property that is true if the current record is the
last. It is also true if there are no records in the RecordSet.
Then we make the program add the "Name" field of all records to the list box by adding the
current records field "Name" and moving to the next record. You ask for a field of a RecordSet
by putting a ! between the name of the RecordSet object and the na me of the field. The while
loop checks to see if there are more records to add.
The primary key for all the records in order to search for a record.
Put a text box somewhere on the form and call it "txtPhone". Then copy the following code to
the project.
This will display the phone number of the selected person when clicking in the list box. It uses
the FindFirst method of the RecordSet object. This takes a string parameter that is like what is
after WHERE in a SQL expression. You state the field that you want to search in (here "ID"),
then the evaluation criteria (here "=") and last the value to search for (here the ItemData of the
selected item in the list box).
So what we did was to search for the record with the "ID" field value that was the same as the
ItemData property of the selected item in the list box. Then we show the value of the "Phone"
field in the text box.
You will probably want to be able to update some value of some field when doing database
programming. This is done with Edit and Update. We will try to change the value of the "Phone"
field by editing the text in the text box and clicking a button.
Put a command button on the form and name it "cmdUpdate". Then copy the following code to
the project.
Could it be that simple? Yes. This changes the phone number of our selected person. Or to put it
technically: This changes the value of the "Phone" field of our current record. Imagine the
current record being a set of boxes, with a field in each box. The Edit method takes the lid off all
of the boxes and Update puts them back on. When we write rsMyRS!Phone = txtPhone.Text we
replace the content of the "Phone" box with the content in the text box.
Deleting and Adding records
Deleting
Deleting records couldn't be simpler. To delete the current record you just invoke the Delete
method of the RecordSet object. We will put this feature in our little project. Make one more
command button named "cmdDelete" and the following code will do the work of deleting our
currently selected person.
Adding
Adding records is much like updating, except you use AddNew instead of Edit. Let's add one
more command button to our application. Let's call it...errh...let me see...yea! "cmdNew" =).
Here is the code that adds a new record.
Private Sub cmdNew_Click()
rsMyRS.AddNew
rsMyRS!Name = "A New Person"
lstRecords.AddItem rsMyRS!Name
lstRecords.ItemData(lstRecords.NewIndex) = rsMyRS!ID rsMyRS!Phone
= "Person's Phone Number"
rsMyRS.Update End
Sub
The AddNew method takes a set of new boxes and adds them to our RecordSet. We then put
some new values in them and close the lids with Update. As you can see we never stated any
value for "ID", but as you remember, this is a field of type "Counter" which automatically gets a
unique value.
RESULT :
Ex.No 8 Database design using EER-to-ODB mapping / UML class diagrams
Date:
Aim:
Procedure:
Result :
EX.NO 9 Object features of SQL-UDTs and sub-types, Tables using UDTs, Inheritance,
Date: Method definition
Aim:
Procedure:
-- if created
idno NUMBER,
name VARCHAR2(30),
phone VARCHAR2(20),
NOT FINAL;
BEGIN
RETURN idno;
END;
BEGIN
END;
Result:
EX.NO 10 Querying the Object-relational database using Objet Query language
Date:
Aim:
Procedure:
Result:
EX.NO 10 Querying the Object-relational database using Objet Query language
Date:
Aim:
To implement the Querying the Object-relational database using Objet Query language.
Procedure:
Result:
Thus the relation is created as object and the SQL query is manipulated.