31
SECTION 1 UNIX Lab Session 1 : Ex 1: Explore all the UNIX commands given in this manual. Ans: 1> Files ls --- lists your files ls -l --- lists your files in 'long format', which contains lots of useful information, e.g. the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified. ls -a --- lists all files, including the ones whose filenames begin in a dot, which you do not always want to see. There are many more options, for example to list files by size, by date, recursively etc. Cat - combine files more filename --- shows the first part of a file, just as much as will fit on one screen. Just hit the space bar to see more or q to quit. You can use /pattern to search for a pattern. emacs filename --- is an editor that lets you create and edit a file. mv filename1 filename2 --- moves a file (i.e. gives it a different name, or moves it into a different directory (see below) cp filename1 filename2 --- copies a file rm filename --- removes a file. It is wise to use the option rm -i, which will ask you for confirmation before actually deleting anything. You can make this your default by making an alias in your .cshrc file. diff filename1 filename2 --- compares files, and shows where they differ wc filename --- tells you how many lines, words, and characters there are in a file chmod options filename --- lets you change the read, write, and execute permissions on your files. chmod o+r filename will make the file readable for everyone, and chmod o-r filename will make it unreadable for others again. Note that for someone to be able to actually look at the file the directories it is in need to be at least executable. File Compression o gzip filename --- compresses files, so that they take up much less space. Usually text files compress to about half their original size, but it depends very much on the size of the file and the nature of the contents. There are other tools for this purpose, too (e.g. compress), but gzip usually gives the highest compression rate. Gzip produces files with the ending '.gz' appended to the original filename. o gunzip filename --- uncompresses files compressed by gzip. o gzcat filename --- lets you look at a gzipped file without actually having to gunzip it (same as gunzip -c). You can even print it directly, using gzcat filename | lpr printing o lpr filename --- print. Use the -P option to specify the printer name if you want to use a printer other than your default printer. For example, if you want to print double-sided, use 'lpr -Pvalkyr-d', or if you're at CSLI, you may want to use 'lpr -Pcord115-d'. See 'help printers' for more information about printers and their locations. o lpq --- check out the printer queue, e.g. to get the number needed for removal, or to see how many other files will be printed before yours will come out o lprm jobnumber --- remove something from the printer queue. You can find the job number by using lpq. Theoretically you also have to specify a printer name, but this isn't necessary as long as you use your default printer in the department. o genscript --- converts plain text files into postscript for printing, and gives you some options for formatting. Consider making an alias like alias ecop 'genscript -2 -r \!* | lpr -h -Pvalkyr' to print two pages on one piece of paper. o dvips filename --- print .dvi files (i.e. files produced by LaTeX). You can use dviselect to print only selected pages. Directories, like folders on a Macintosh, are used to group files together in a hierarchical structure. mkdir dirname --- make a new directory cd dirname --- change directory. You basically 'go' to another directory, and you will see the files in that directory when you do 'ls'. You always start out in your 'home directory', and you can get back there by typing 'cd' without arguments. 'cd ..' will get you one level up from your current position. You don't have to walk along step by step - you can make big leaps or avoid walking around by specifying pathnames. pwd --- tells you where you currently are. 2> Display contents of files Cat - copy file to display device. Vi - Screen editor for modify text files. More - show text files on display terminal with paging control. Head - show first few lines of a file. Tail - show last few lines of file or reverse line order. Grep - display lines that match a pattern. 3> Finding things ff --- find files anywhere on the system. This can be extremely useful if you've forgotten in which directory you put a file, but do remember the name. ff -p you don't even need the full name, just the beginning. This can also be useful for finding other things on the system, e.g. documentation. grep string filename(s) --- looks for the string in the files. e.g. finding the right file among many, figuring out which is the right version of something, and even doing serious corpus work. grep comes in several varieties ( grep, egrep, and fgrep) and has a lot of very flexible options. Check out the man pages if this sounds good to you. Date - show date and time.

MCSL-045 Lab Manual

Embed Size (px)

DESCRIPTION

ignou solved assnigment

Citation preview

Page 1: MCSL-045 Lab Manual

SECTION – 1

UNIX Lab

Session 1 :

Ex 1: Explore all the UNIX commands given in this manual.

Ans:

1> Files

ls --- lists your files

ls -l --- lists your files in 'long format', which contains lots of useful information, e.g. the exact size of the file, who

owns the file and who has the right to look at it, and when it was last modified.

ls -a --- lists all files, including the ones whose filenames begin in a dot, which you do not always want to see.

There are many more options, for example to list files by size, by date, recursively etc.

Cat - combine files

more filename --- shows the first part of a file, just as much as will fit on one screen. Just hit the space bar to see

more or q to quit. You can use /pattern to search for a pattern.

emacs filename --- is an editor that lets you create and edit a file. mv filename1 filename2 --- moves a file (i.e.

gives it a different name, or moves it into a different directory (see below)

cp filename1 filename2 --- copies a file

rm filename --- removes a file. It is wise to use the option rm -i, which will ask you for confirmation before actually

deleting anything. You can make this your default by making an alias in your .cshrc file.

diff filename1 filename2 --- compares files, and shows where they differ

wc filename --- tells you how many lines, words, and characters there are in a file

chmod options filename --- lets you change the read, write, and execute permissions on your files. chmod o+r

filename will make the file readable for everyone, and chmod o-r filename will make it unreadable for others again.

Note that for someone to be able to actually look at the file the directories it is in need to be at least executable.

File Compression

o gzip filename --- compresses files, so that they take up much less space. Usually text files compress to

about half their original size, but it depends very much on the size of the file and the nature of the contents.

There are other tools for this purpose, too (e.g. compress), but gzip usually gives the highest compression

rate. Gzip produces files with the ending '.gz' appended to the original filename.

o gunzip filename --- uncompresses files compressed by gzip.

o gzcat filename --- lets you look at a gzipped file without actually having to gunzip it (same as gunzip -c).

You can even print it directly, using gzcat filename | lpr

printing

o lpr filename --- print. Use the -P option to specify the printer name if you want to use a printer other than

your default printer. For example, if you want to print double-sided, use 'lpr -Pvalkyr-d', or if you're at

CSLI, you may want to use 'lpr -Pcord115-d'. See 'help printers' for more information about printers and

their locations.

o lpq --- check out the printer queue, e.g. to get the number needed for removal, or to see how many other

files will be printed before yours will come out

o lprm jobnumber --- remove something from the printer queue. You can find the job number by using lpq.

Theoretically you also have to specify a printer name, but this isn't necessary as long as you use your

default printer in the department.

o genscript --- converts plain text files into postscript for printing, and gives you some options for

formatting. Consider making an alias like alias ecop 'genscript -2 -r \!* | lpr -h -Pvalkyr' to print two

pages on one piece of paper.

o dvips filename --- print .dvi files (i.e. files produced by LaTeX). You can use dviselect to print only

selected pages.

Directories, like folders on a Macintosh, are used to group files together in a hierarchical structure.

mkdir dirname --- make a new directory

cd dirname --- change directory. You basically 'go' to another directory, and you will see the files in that directory

when you do 'ls'. You always start out in your 'home directory', and you can get back there by typing 'cd' without

arguments. 'cd ..' will get you one level up from your current position. You don't have to walk along step by step -

you can make big leaps or avoid walking around by specifying pathnames.

pwd --- tells you where you currently are.

2> Display contents of files

Cat - copy file to display device.

Vi - Screen editor for modify text files.

More - show text files on display terminal with paging control.

Head - show first few lines of a file.

Tail - show last few lines of file or reverse line order.

Grep - display lines that match a pattern.

3> Finding things

ff --- find files anywhere on the system. This can be extremely useful if you've forgotten in which directory you put

a file, but do remember the name.

ff -p you don't even need the full name, just the beginning. This can also be useful for finding other things on the

system, e.g. documentation.

grep string filename(s) --- looks for the string in the files. e.g. finding the right file among many, figuring out which

is the right version of something, and even doing serious corpus work. grep comes in several varieties (grep, egrep,

and fgrep) and has a lot of very flexible options. Check out the man pages if this sounds good to you.

Date - show date and time.

Page 2: MCSL-045 Lab Manual

History - list of previously executed commands.

Man - show on-line documentation by program name.

4> About User / People

w --- tells you who's logged in, and what they're doing. Especially useful: the 'idle' part. This allows you to see

whether they're actually sitting there typing away at their keyboards right at the moment.

who --- tells you who's logged on, and where they're coming from. Useful if you're looking for someone who's

actually physically in the same building as you, or in some other particular location.

Who am i--- who is logged onto this system.

finger username --- gives you lots of information about that user, e.g. when they last read their mail and whether

they're logged in. Often people put other practical information, such as phone numbers and addresses, in a file called

.plan. This information is also displayed by 'finger'.

last -1 username --- tells you when the user last logged on and off and from where. Without any options, last will

give you a list of everyone's logins.

talk username --- lets you have a (typed) conversation with another user

write username --- lets you exchange one-line messages with another user

elm --- lets you send e-mail messages to people around the world.

5> About your (electronic) self

whoami --- returns your username. Sounds useless, but isn't. You may need to find out who it is who forgot to log

out somewhere, and make sure *you* have logged out.

finger & .plan files of course you can finger yourself, too. That can be useful e.g. as a quick check whether you got

new mail.

passwd --- lets you change your password, which you should do regularly (at least once a year).

ps -u yourusername --- lists your processes. Contains lots of information about them, including the process ID,

which you need if you have to kill a process.

kill PID --- kills (ends) the processes with the ID you gave. This works only for your own processes, of course. Get

the ID by using ps.

quota -v --- show what your disk quota is, how much you're actually using, and in case you've exceeded your quota,

how much time you have left to sort them out.

du filename --- shows the disk usage of the files and directories in filename (without argument the current directory

is used). du -s gives only a total.

last yourusername --- lists your last logins. Can be a useful memory aid for when you were where, how long you've

been working for, and keeping track of your phonebill if you're making a non-local phonecall for dialling in.

Ex 2: Create a directory.

Ans: To create a directory, use the mkdir command.

For example : mkdir Student

Ex 3: Create a subdirectory in the directory created.

Ans: Step-1: first create a directory

For ex:- mkdir rootdirectory

Step-2: then enter in rootdirectory

For ex: cd rootdirectory

Step-3: then create another directory

For ex: mkdir subdirectory.

Ex 4: Change your current directory to the subdirectory. Ans: You may create a subdirectory within any directory where you have write permission.

For example: mkdir /Student/Subdirectory1

Ex 5: Display the calendar for the current month.

Ans: To display Calender for the current month use the CAL command.

% CAL

Ex 6: Get a directory listing of the parent directory. Ans: To get the Directory listing of the parent directory, use the command

ls - list contents of directory.

Goto the parent directory and use ls command.

% ls

Ex 7: How many users were logged onto your system?

Ans: To see all the other users that are currently connected to system simply use

% who command.

Ex 8: Display your name in the form of a banner.

Ans: The banner Command displays a large ASCII art version of input text. There are two common

varieties: one, which prints text horizontally for display to a terminal, and another which prints text in

much larger letters for output to a line printer.

% banner Student

% banner –w80 a

Page 3: MCSL-045 Lab Manual

Ex 9: Display the name of device name of your terminal.

Ans: To display the device name of the terminal, use the tty command:

Ex 10: Move to the root directory.

Ans: To move to root directory use CD command.

% cd

Session 2 :

Ex 11: Change your directory to the directory exercises. Create a file called example1 using the cat command

containing the following text:

water, water everywhere and all the boards did shrink; water, water everywhere, No drop to drink.

Ans: MV mydirectory exercise

Step-1: cat example1

Step-2: type the text

Step-3: Press ctrl+D for save

Ex 12: Use the man command to obtain further information on the finger command. Ans: The man command displays information from the reference manuals. It displays complete manual pages that you select

by name, or one-line summaries selected either by keyword (-k), or by the name of an associated file (-f). If no manual

page is located, man prints an error message.

% man command name

% man finger

Finger - display information about local and remote users Ex 13: List all the processes that are presently running.

Ans: To find out information about the processes running on the system use the ps command.

% ps

Ex 14: List the text files in your current directory.

Ans: Find/ usr –type –name *.txt print

Ex 15: Make a copy of any text file.

Ans: To copy any text file to another text file use the cp command:

cp file1 file2 is the command which makes a copy of file1 in the current working directory and calls

it file2.

First CD to your current directory:

% cd ~/Student

Then, copy the text file,

% cp /unix/examples/copy.txt.

(Note: Don't forget the dot (.) at the end. Remember, in UNIX, the dot means the current

directory.)

ELSE

% cp file1 file2.

Ex 16: Rename one of your text files in the current directory.

Ans: To rename file in current directory use MV move command:

% mv file.txt filename.txt mv junk.txt newfile

Ex 17: Delete an unneeded copy of a file.

Ans: To delete a file use the rm remove command:

% rm file.txt

Ex 18: Print out any file on paper.

Ans: To print a file in UNIX uses the lpr command: % lpr filename.txt

Ex 19: Send a message to another user on your UNIX system, and get them to reply.

Ans: The mail command enables the user to send and receive electronic mail messages to and from

users on both the Unix system and remote users.

To send a message to a user on your system, type:

% mail username

The cursor will move to the next line, and you will get a Subject: prompt. You can now type in the

subject of your message, and then press <RETURN>. The cursor will go to the start of the next line

and there will be no prompt. You now type in the text of your message. Terminate each line with

<RETURN>. When you have finished the text of the message, type an end-of-file character (usually

^D), or a full-stop character.

There are several commands you can type while entering mail:

<CTRL/Z> will cancel the message, and leave the text in a file named dead.letter.

Page 4: MCSL-045 Lab Manual

^e invokes a text editor to edit your message.

~v invokes a screen editor to edit your message.

~f reads the contents of the message you have just read, into your message text. ~r file reads contents of file into your message text.

Ex 20: Create a small text file and send it to another user.

Ans: To create a text file, use the cat command:

% cat > Student

To send this file to another user user 1:

% mail user1 < Student

Use the re-direction to output stream operation.

Session 3 :

Ex 21: When you receive a message, save it to a file other than your mailbox. Ans: We can open all received message by

$mail

Then we save a mail message to a file by

$sx

UNIX uses two mailboxes to hold mail messages

system mailbox (/usr/spool/mail/)

user mail box (..../.../mbox) Ex 22: Send a message to a user on a different computer system.

Ans: Mail mca11 ttyp5

Subject: Hello

How are you?

Then press ctrl+D .

Sending mail to users on other computer systems is simple using mail. Simply type the full address

of the remote user.

% mail [email protected]

Ex 23: Try to move to the home directory of someone else in your group. There are several ways to do this, and

you may find that you are not permitted to enter certain directories. See what files they have, and what the file

permissions are.

Ans: To move to the home directory of someone else in the group:

% cd ~ user1

To list the files in the directory and their permissions:

% ls –ldg

Ex 24: Try to copy a file from another user’s directory to your own.

Ans: @pwd

User/mca11

$cd abhishek

$ cp xyz.txt/user2/mca4

Ex 25: Set permissions on all of your files and directories to those that you want. You may want to give read

permission on some of your files and directories to members of your group.

Ans: $chmod –R 777 abc.txt

Ex 26: Create a number of hierarchically related directories and navigate through them using a combination of

absolute pathnames (starting with "/") and relative pathnames.

Ans: - $mkdir/user/mca11/helpme

$cd user/mca11/helpme

Ex 27: Try using wildcards (“*” and possibly “?”).

Ans: 1. This command will display the listing of all files having extension .txt.

$ls *.txt 2. Lists only the files Lit and bit. The file snit was not listed because it has two characters before "it". ls ?it

Ex 28: Put a listing of the files in your directory into a file called filelist. (Then delete it!)

Ans: Using the CP command,

% cp ~Student/directory1* filelist

% rm filelist

Ex 29: Create a text file containing a short story, and then use the spell program to check the spelling of the

words in the file.

Page 5: MCSL-045 Lab Manual

Ans: $cat> story.txt

Type the text

Press ctrl+D to save.

$spell story.txt

Ex 30: Redirect the output of the spell program to a file called errors. Ans: $spell story.txt > error

Session 4 :

Ex 31: Type the command ls -l and examine the format of the output. Pipe the output of the command ls -l to the

word count program WC to obtain a count of the number of files in your directory.

Ans: The WC command is used to print the number of lines, words, and characters in a file.

Syntax: wc [options] filename

To find the number of files in a directory, enter

ls -l | wc –c

ls –l : For a long listing that shows file protections, size, and date Ex 32: Use cut to strip away the reference material and leave just the text field.

Ans: Cut command is typically used to extract a certain range of characters from a line, usually

from a file. Syntax: % cut [-b] [-c] [-f list] [-n] [-d delim] [-s] [file]

command - $cat – F 1-3-d

Ex 33: Use tr to strip away any tags that are actually in the text (e.g., attached to the words), so that you are left

with just the words.

Ans: The tr command (translate characters) is one of the true Unix filters. It copies its standard

input to its standard output, while replacing the first character specified on the command line with

the second character specified.

Let’s consider the text file to be example1.txt,

$ echo <B></B> this is the tag for bold text

Cat example1.txt | tr ‘<a-z>’ ‘a-z’

Output: B/B this is the tag for bold text

Ex 34: Set a file to be read-only with the chmod (from change mode) command. Interpret the file permissions

displayed by the ls -l command.

Ans: To set the file to be read-only to all,

% chmod a+r file1

To see the permissions of the file, use the ls –l command.

Ex 35: Delete one or more directories with the rmdir (from remove directory) command. See what happens if the

directory is not empty. Experiment (carefully!) with the rm -r command to delete a directory and its content.

Ans: $rmdir

$rm –r

$rm –r abc

Ex 36: Experiment with redirecting command output (e.g., ls -l >file1). Try ">> “instead of” >" with an existing

text file as the output.

Ans: $ ls –l>> file

This will append the text in existing file.

Ex 37: See whether upper-case versions of any of these commands work as well as the lower-case versions.

Ans: UNIX is *ALWAYS* case-sensitive.

If you want to list your files with the `ls' command, if you enter LS you will be told "command not

found."

Ex 38: Use the who command to see users logged into the system.

Ans: $who

Mca1 ttyp7 mar20 15:14

Mca2 ttyp5 mar19 11:11

Mca2 ttyp6 mar16 11:10

Mca3 ttyp7 mar11 13:11

Ex 39: Pipe the output of the who command to the sort command.

Ans: - $who | sort -4

To pipe the output of the who command to the input of the sort command:

%who | sort >file1

Ex 40: Search for your login name in whofile using the grep command.

Page 6: MCSL-045 Lab Manual

Ans: . The grep command displays the name of the file containing the matched line if you specify

more than one name in the File parameter.

$who >who file

$grep student whofile

Or

$who |grep student

Session 5 :

Ex 41: Compare two text files with the diff command. Ans: The diff command is used to display two files and prints the lines that are different.

$diff file1 file2

When you run diff on file1 and file2, the following output is produced:

$ diff file1 file2

3c3

< walnuts

--

> grapes Ex 42: Count lines, words, and characters in a file with the wc command.

Ans: - $wc –c for characters

$wc –l for lines

$wc –w for wordss

Ex 43: Display your current environment variables with the following command: set or env.

Ans: $set or $env both are same

$set or $env

Output:- HOME=/user1/mca22

HUSHLOGIN= FALSE

HZ=100

TFS=

LOG NAME= mca22

MAIL= /user/spool/mail/mca22

MAILCHECK= 600

MF_ADM=odm.cat@unix

Msg-Mail=1

Ms_PROFILE=1

OPTLND=1

PATH=/bin:/usrer1/mca22/bin:

PS1=$

PS2=>

SHELL=/bin/sh

TERM=ansi

TZ=ESTSEDT

Ex 44: Concatenate all files in a directory redirected to /dev/null and redirecting standard error to “errorFile”?

Ans: To concatenate files in Unix use the cat command.

% cat *> /dev/null/errorfile

* All files in directory.

Ex 45: Display information on yourself or another user with the finger command.

Ans: The finger displays the user's login name, real name, terminal name and write status.

$finger

Login name tty idle login time Where

Mca1 *P20 15:49 22:11 192.168.22.3

Mca2 *P21 12:22 21:11 192.168.2.3

Mca3 *P23 14:49 12:11 192.168.2.5

Mca4 *P26 11:49 22:11 192.168.2.2

Ex 46: If you wish, experiment with sending and receiving mail using the pine email program.

Ans: Pine is an easy to use, character based mail client. It supports full screen editing of messages,

binary attachments (such as GIF or ZIP files), and other advanced message system features that

were not possible using older electronic mail clients.

Features of pine:

Full Screen Capabilities

Safety for New Users – confirmation of actions.

On-Line Help

Sending Attachments with Your Message – MIME encoding

Name Recognition (Address Books)

Message Browsing

Page 7: MCSL-045 Lab Manual

Message Printing

Saving Messages

Pine is a menu based screen and you should look at the bottom of the screen where valid

menu commands are shown

Using PINE:

1. Type pine at the UNIX prompt and you will see the pine screen.

2. Enter user name and password.

3. To compose mail, Use the compose command C - COMPOSE MESSAGE to compose a

message. After composing, to send the mail, use Ctrl+X to send your message. Can you

see the choice ^X Send in the menu bar at the bottom of the screen.

4. To see the mails you have received use the L - LIST FOLDERS command from the main

menu to see your folders and choose the INBOX folder. Use N - NextMsg to read the next

message or P - PrevMsg to read previous message.

5. To reply use the R - Reply command, and to forward mail use the F - Forward

command.

6. You can use the D - Delete command to delete your unwanted mails.

7. If you want to print (or read the message you want to print, then choose the command O

- OTHER CMDS, then choose command % - Print. At the bottom you will see the message

Print message n using "attached-to-ansi" ? , where n is the message number. Answer

it with Y [Yes] . A pop-up print setup screen will appear, and click OK button. Your mail

content will then be printed from your local printer.

8. You can exit pine by using Q - QUIT command when you are in the main menu.

Ex 47: Delete all the files in the current directory whose name ends in “.bak”.

Ans: $cat>a.back Sss Ctrl+D

$ls –l *.back $rm *.back

Ex 48: Display lines 10 to 14 of any file which contains 25 lines. Ans: $tail +10 file name | head -5

$head -10 file1| tail -14 file

Ex 49: Count how many lines contain the word science in a word file science.txt.

Ans: First find the word using the grep command and then pie it using the wc command.

% grep science science.txt | wc –l

Ex 50: List the statistics of the largest file (and only the largest file) in the current directory.

Ans: $ls –l| grep ‘n’ |sort>m1

$cat –d –f 4|sort m1;tail –l

Session 6 :

Ex 51: Kill any process with the help of the PID and run any process at the background.

Ans: $pwd

$kill 22556

$vi abc.txt

$date &

Ex 52: Select a text file and double space the lines.

Ans: Use the SED command to double space the lines in a text file.

% sed filename

Ex 53: List all the users from /etc/passwd in the alphabetically sorted order.

Ans: $cat /etc/password|sort

Ex 54: Create a file with duplicate records and delete duplicate records for that file..

Ans: $cat b11.txt

Abhishek abhishek abhishek

Ctrl+D to save.

$uniq –c b11.txt

Abhishek

$uniq abc.txt>ab1.txt

$Cp ab.txt abc.txt

$cat abc.txt

Ex 55: Use the grep command to search the file example1 for occurrences of the string “water”.

Ans: $cat>prog.sh

Page 8: MCSL-045 Lab Manual

For I in cat example1

Do

Echo $i>>ex1

Done

Ctrl+D

$sh prog.sh

$cat ex1|grep –c “water”

$grep water example1

Ex 56: Write grep commands to do the following activities:

• To select the lines from a file that have exactly two characters.

Ans: $grep ‘^.$’ n1

• To select the lines from a file that start with the upper case letter.

Ans: $grep ‘[A-Z] ^1

• To select the lines from a file that end with a period.

Ans: $grep $n1

• To select the lines in a file that has one or more blank spaces.

Ans: $grep ‘ ‘n1

• To select the lines in a file and direct them to another file which has digits as one of the characters in that

line.

Ans: $grep ‘[0-9]’ n1>n2

Ex 57: Make a sorted wordlist from the file.

Ans: $tr ‘A-Z’ ‘a-z’ < file1|tr –cs ‘a-z’ ‘\02’|sort |uniq –c>file2

Ex 58: Try to execute the example shell scripts given in this manual. Ans: $vi nv

Echo “Enter any no.”

Read a

Echo “Number is 4a”

Ex 59: Write a shell script that searches for a single word pattern recursively in the current directory and displays

the no. of times it occurred. Ans: $grep –r ‘ABC’

Ex 60: Write a shell script to implement the DISKCOPY command of DOS. Ans:

Session 7 :

Ex 61: Write a shell script that accepts a string from the terminal and echo a suitable message if it doesn’t have at

least 5 characters including the other symbols.

Ans: $vi abc

Echo “Enter the string”

Read s

C=`expr $s |wc –c`

C=`expr $c -1`

If Test $c –ge 5

Then

Echo “String is valid”

Else

Echo “String is invalid”

Fi

:wq Ex 62: Write a shell script to echo the string length of the given string as argument.

Ans: $Vi xyz

Echo “enter the String”

Read a

C=’echo $a |wc –c’

C=`expr $c -1`

Echo $c

:wq

Ex 63: Write a shell script that accepts two directory names as arguments and deletes those files in the first

directory which are similarly named in the second directly. Note: Contents should also match inside the files.

Page 9: MCSL-045 Lab Manual

Ans: $Vi abc

Echo “enter the fist Dir”

Read a

Echo “Enter the second Dir”

Read b

Ls $a >> aa

Ls $b >> bb

For ‘in comm. -1-2 aabb’

Do

Q=’emp –s/usrer/bca/hour/s1/user1/bca1/abhi/$i’

Echo $q

If Test $q –eq 0

Sun/user1/bca1/hour/$ls

Sun/user1/bca1/abhi/&i

Else

fi

Done

:wq

Ex 64: Write a shell script to display the processes running on the system for every 30 seconds, but only for 3

times.

Ans: Vi process

I=”0”

While Test $i –le 3

Do sleep 5

Ps

i=`expr $i +1`

done

Ex 65: Write a shell script that displays the last modification time of any file.

Ans: Ls –l put|cat –c -45 -48

Ex 66: Write a shell script to check the spellings of any text document given as an argument.

Ans: Echo “enter the file”

Read a

Spell $a> error

Cut error

Ex 67: Write a shell script to encrypt any text file.

Ans: $ crypt -puu2 < file9

This will encrypt the file using the puu2 key.

Or

$ crypt file9

Enter the key: puu2

This will encrypt the file.

Ex 68: Combine the above commands in a shell script so that you have a small program for extracting a wordlist. Ans:

Ex 69: Write a shell script which reads the contents in a text file and removes all the blank spaces in them and

redirects the output to a file.

Ans: W=`wc –w Test`

Echo “No of word $w”

C=1

Set ‘cat jay’

While test $c –le $w

Do

Echo –n $i>>jay

C=`expr $c +1`

Done

Cut jay

Or

Vi xyz

For I in ‘cat jay’

Do

Echo –n 4i

done

Page 10: MCSL-045 Lab Manual

Ex 70: Write a shell script that changes the name of the files passed as arguments to lowercase. Ans: Echo $i>temp

Tr “[:uppr:]” “[:lowe:]” [temp]

Mv /user/mca2/$i/user/mca2/$a

Session 8 :

Ex 71: Write a shell script to translate all the characters to lower case in a given text file.

Ans: Echo enter a text file

Read file

If [1 $file]

Then

Echo 4file not a file

Exit

Fi

Cat $file |tr ‘[A-Z]’ ‘[a-z]’ Ex 72: Write a shell script to combine any three text files into a single file (append them in the order as they

appear in the arguments) and display the word count.

Ans: # //bin/bash

File1=$1

File2=$2

File3=$3 out- ‘output $1’

Count=0

If [$# -ne 3]

Then

Echo “$(base name $o) file1 file 2file3”

Exit1

Fi

If [!=$file]

Then

Echo ‘$file! Not a file’

Exit2

Fi

If[! –f $file2]

Then

Echo “$file2 not file!”

Exit 3

Fi

If [1- f $file]

Then

Echo $file3 not a file!”

Exit2

Fi

$file1 $file 2$file3?? $out

Count=4(cat $out|wc –w)

Echo “count words written to out!”

Ex 73: Write a shell script that, given a file name as the argument will write the even numbered line to a file with

name evenfile and odd numbered lines to a file called oddfile.

Ans:

Ex 74: Write a shell script which deletes all the even numbered lines in a text file.

Ans:

Ex 75: Write a script called hello which outputs the following:

• your username

• the time and date

• who is logged on

• also output a line of asterices (*********) after each section.

Ans:

Ex 76: Put the command hello into your .login file so that the script is executed every time that you log on.

Ans:

Ex 77: Write a script that will count the number of files in each of your subdirectories.

Ans:

Ex 78: Write a shell script like a more command. It asks the user name, the name of the file on command prompt

and displays only the 15 lines of the file at a time on the screen. Further, next 15 lines will be displayed only when

the user presses the enter key / any other key.

Page 11: MCSL-045 Lab Manual

Ans:

Ex 79: Write a shell script that counts English language articles (a, an, the) in a given text file. Ans:

Ex 80: Write the shell script which will replace each occurrence of character c with the characters chr in a string

s. It should also display the number of replacements.

Ans:

Session 9 :

Ex 81: Write the shell program unique, which discards all but one of successive identical lines from standard

input and writes the unique lines to standard output. By default, unique checks the whole line for uniqueness.

For example, assuming the following input:

List 1 List 2 List 2 List 3 List 4 List 4 List 2

unique should produce the following output as follows:

List 1 List 2 List 3 List 4 List 2 Ans: Ex 82: Rewrite the unique program so that it can optionally accept a file name on the command line and redirect

the output to that file. Ans:

Ex 83: Write the shell program which produces a report from the output of ls -l in the following form:

• Only regular files, directories and symbolic links are printed.

• The file type and permissions are removed.

• A / character is appended to each directory name and the word DIR is printed at the beginning of the

line.

• A @ character is appended to each symbolic link name and the word LINK is printed at the beginning

of the line.

At the end of the listing, the number of directories, symbolic links, regular files and the total size of regular files

should be reported.

Ans:

Ex 84: Write the shell program which removes all the comments from a simple C program stored in your current

directory. You can assume that the C source code contains only syntactically correct comments:

• starting with //, ending with a newline

• starting with /*, ending with */ (can be multi-line)

• nesting of comments is not allowed.

Make sure that C source code is not changed.

Ans:

Ex 85: Write a shell program that outputs all integers up to the command line parameter starting from 1 and also

should output the same numbers in the reverse order.

Ans:

Session 10 :

Ex 86: Write a shell program to concatenate to two strings given as input and display the resultant string along

with its string length.

Ans:

Ex 87: Write a shell program to find the largest integer among the three integers given as arguments.

Ans:

Ex 88: Write a shell program to sort a given file which consists of a list of numbers, in ascending order. Ans:

Ex 89: Write a shell program to simulate a simple calculator. Ans:

Ex 90: Write a shell program to count the following in a text file.

• Number of vowels in a given text file.

• Number of blank spaces.

• Number of characters.

• Number of symbols.

• Number of lines Ans:

Page 12: MCSL-045 Lab Manual

SECTION – 2

DBMS Lab

Session 1 : Sub Queries and Joins

Ex 1: Please attempt the following problems for the teacher, class and pay scale relations given in this section.

Ans: Table Creation:

-- Create table

create table TEACHER

(

T_NO VARCHAR2(3) not null,

F_NAME VARCHAR2(50),

L_NAME VARCHAR2(25),

SALARY NUMBER,

SUPERVISIOR VARCHAR2(3),

JOININGDATE DATE,

BIRTHDATE DATE,

TITLE VARCHAR2(3),

INC NUMBER

)

tablespace SYSTEM

pctfree 10

pctused 40

initrans 1

maxtrans 255

storage

(

initial 64K

minextents 1

maxextents unlimited

);

-- Create/Recreate primary, unique and foreign key constraints

alter table TEACHER

add constraint TEACHER_PK primary key (T_NO)

using index

tablespace SYSTEM

pctfree 10

initrans 2

maxtrans 255

storage

(

initial 64K

minextents 1

maxextents unlimited

);

-- Create table

create table CLASS

(

CLASS_NO VARCHAR2(3) not null,

T_NO VARCHAR2(3),

ROOM_NO VARCHAR2(3)

)

tablespace SYSTEM

pctfree 10

pctused 40

initrans 1

maxtrans 255

storage

(

initial 64K

minextents 1

maxextents unlimited

);

-- Create/Recreate primary, unique and foreign key constraints

alter table CLASS

add constraint CLASS_PK primary key (CLASS_NO)

using index

Page 13: MCSL-045 Lab Manual

tablespace SYSTEM

pctfree 10

initrans 2

maxtrans 255

storage

(

initial 64K

minextents 1

maxextents unlimited

);

alter table CLASS

add constraint CLASS_FK foreign key (T_NO)

references TEACHER (T_NO);

-- Create table

create table PAYSCALE

(

MIN_LIMIT NUMBER,

MAX_LIMIT NUMBER,

GRADE VARCHAR2(5) not null

)

tablespace SYSTEM

pctfree 10

pctused 40

initrans 1

maxtrans 255

storage

(

initial 64K

minextents 1

maxextents unlimited

);

-- Create/Recreate primary, unique and foreign key constraints

alter table PAYSCALE

add constraint PAYSCALE_PK primary key (GRADE)

using index

tablespace SYSTEM

pctfree 10

initrans 2

maxtrans 255

storage

(

initial 64K

minextents 1

maxextents unlimited

);

Table: Teacher

t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, title

Table: Class

class_no, t_no, room_no

Table: Payscale

min_limit, max_limit, grade

(a) Display the name of the teacher(s) who is (are) the youngest among all the teachers.

Ans: SELECT f_name, l_name

FROM teacher WHERE birthdate=(SELECT MIN(birthdate) FROM teacher);

(b) Display details of all the teachers who have the same job title as that of ‘Jaideep’

Ans: SELECT * FROM teacher

WHERE title = (SELECT title FROM teacher WHERE LOWER(f_name)=’jaideep’);

(c) Display the list of all the teachers who have joined after ‘10-Jul-95’ and whose salary is equal to that of any of

the teachers who joined before ‘10-Jul-95’. Ans: Select * from teacher

where join_date > ’10-jul-1995’ and salary = any

(select salary from teacher where joining date < ’10-jul-1995’);

(d) Use a correlated query to determine the teachers who are not class teachers.

Page 14: MCSL-045 Lab Manual

Ans: select * from teacher

where title not in ('class teacher');

(e) Identify all those teachers who are in grade ‘B’.

Ans: select distinct *from teacher,payscale

where grade='B'

(f) Display the names and numbers of all teachers who are class teachers and are in grade ‘C’.

Ans: select t_no,f_name

from teacher t, payscale p where p.grade = 'C' AND t.salary = (select salary from teacher * where salary BETWEEN

'10000' AND '17999')

(g) Display the names of all teachers who are supervisors.

Ans: select f_name ||' '|| l_name as Name

from teacher where title in ('supervisor');

(h) Display the teacher id and salaries of all those teachers who are in grade ‘A’ or ‘C’ and who have at least two

L’s in their names.

Ans: select t_no as Teacher_Number, salary

from teacher where (salary between 10000 and 15000 or salary between 7000 and 10000) and f_name

like ‘%l%l%’;

(i) Display details of all those teachers who are class teachers of classes 1 to 5.

Ans: Select t.t_no, t.f_name, t.l_name, t.salary, t.supervisor, t.joiningdate, t.birthdate, t.title

From teacher t, class c where c.T_NO = t.T_NO and c.CLASS_NO between '1' and '5'

(j) Display the names of all teachers along with their dates of birth whose birthday is in the current month.

Ans: select F_name,L_name

from teacher where to_char (birthdate,'MON') = (select to_char(sysdate,'MON') from dual);

Ex 2: In an Open University a student’s data is to be maintained using relations. The university maintains

data of all the students, their batches, Regional Centres and study centre details. Each batch of students

has one or more representative students. The batches are taught by same or different faculty.

(a) Design and implement the suitable relations for the University. Make and state suitable assumptions.

Ans: 1. CREATE table STUDENT (

STDID VARCHAR2(10) PRIMARY KEY, NAME VARCHAR2(20), ADDRESS VARCHAR2(40), COURSEID VARCHAR2(10), BATCHID VARCHAR2(10), CONSTRAINTS STUDENT_FK FOREIGN KEY(COURSEID) REFERENCES COURSE(COURSEID));

2. CREATE TABLE BATCH (

BATCHID VARCHAR2(10), RCID VARCHAR2(10), SDYID VARCHAR2(10), COURSEID VARCHAR2(10), REPSTDID VARCHAR2(10), CONSTRAINT BATCH_FK FOREIGN KEY(RCID) REFERENCES REGCENT(RCID), FOREIGN KEY(SDYID) REFERENCES SDYCENT(SDYID), FOREIGN KEY(COURSEID) REFERENCES COURSE(COURSEID), * FOREIGN KEY(REPSTDID) REFERENCES STUDENT(STDID));

3. ALTER TABLE BATCH ADD CONSTRAINT BATCH_PK PRIMARY KEY(BATCHID);

4. CREATE TABLE TEACHERS (

TCHID VARCHAR2(10) primary key, TNAME VARCHAR2(20), COURSEID VARCHAR2(10), BATCHID VARCHAR2(10), CONSTRAINTS TEACHER_FK FOREIGN KEY(COURSEID) REFERENCES OURSE(COURSEID), FOREIGN KEY(BATCHID) REFERENCES BATCH(BATCHID));

The following tables were created and the data inserted as under.

SQL> SELECT * FROM STUDENT;

STDID NAME ADDRESS COURSEID BATCHID

Page 15: MCSL-045 Lab Manual

---------- -------------------- ---------------------------- -------------- --------------

STD001 SANZAYA APTEL NILADRI VIHAR M001 B001

STD002 RITA NAYAK NILADRI VIHAR M001 B001

STD003 SRIKANTA PRADHAN SAHID NAGAR MB001 B002

STD004 MIRA AGRAWAL KALPANA SQURE MB001 B002

STD005 NAMITA SAWANT BILAS PUR BB001 B003

STD006 SANDEEP SWAIN MANCHESWAR BB001 B003

STD007 KALICHARAN MURMU SAILESHRI VIHAR CO001 B004

STD008 MAKHUNU SINGH CHENNAI CO001 B004

STD009 KAMALA PRADHAN MUMBAI SC001 B004

STD010 SEKHAR SUMAN DELHI SC001 B005

10 rows selected.

SQL> SELECT * FROM COURSE;

COURSEID COURSENAME COURSEFEE

-----------------------------------------------------------

M001 MCA 10000

MB01 MBA 15000

BB01 BBA 8000

AR01 ARTS 5000

CO01 COMMERCE 7000

SC01 SCIENCE 6000

6 rows selected.

SQL> SELECT * FROM TEACHERS;

TCHID TNAME BATCHID

---------------------------------------------------------------------

TCH001 SUMIT SEHGAL B001

TCH002 ABDUL KALAM B002

TCH003 BASANTA PATEL B003

TCH004 SUMANTA NAYAK B004

TCH005 MANJU MISHRA B005

SQL> SELECT * FROM SDYCENT;

SDYID SDYNAME SDYADDR RCID

---------- ---------- ------------------------------ ---------------------------------

SDY001 KIIT PATIA RC001

SDY002 SCBCOL PURI RC001

SDY003 GMCOL SAMBALPUR RC001

SDY004 KAMALACOL A V NAGAR RC002

SDY005 STEPHENCOL INSTITUTIONAL AREA RC002

SQL> SELECT * FROM REGCENT;

RCID RCNAME RCADDR

---------- ---------- -------------------------------------------------

RC001 BBSR NEAR FORTUNE TOWER

RC002 NDLS MAIDAN GARHI

RC003 MUMBAI SANTACRUZ ROAD

RC004 CHENNAI RAMESWARAM ROAD

RC005 KOLKATA SALTLAKE CITY

SQL> SELECT * FROM BATCH;

BATCHID RCID SDYID COURSEID REPSTDID

---------- ---------- ---------- ---------- ------------------------------------

B001 RC001 SDY001 M001 STD002

B002 RC001 SDY001 MB01 STD003

B003 RC002 SDY003 BB01 STD005

B004 RC004 SDY004 SC01 STD007

B005 RC005 SDY005 CO01 STD009

Ex.2 (b) Write at least 15 queries (they must include at least one query of each type given in this section 2.2)

for the database. Implement these queries using SQL. Also explain the purpose of each query.

Ans: I. Display the details of study centre where a student named ’Sanzaya’ reads; SQL> SELECT * FROM SDYCENT WHERE

SDYID=(SELECT SDYID FROM BATCH

WHERE BATCHID=(SELECT BATCHID FROM STUDENT

WHERE UPPER(NAME) LIKE 'SANZAYA%'));

II. Display the course fee where makhunu singh is admitted. SQL> SELECT COURSEFEE FROM COURSE WHERE

COURSEID=(SELECT COURSEID FROM BATCH WHERE

Page 16: MCSL-045 Lab Manual

BATCHID=(SELECT BATCHID FROM STUDENT WHERE

UPPER(NAME)='MAKHUNU SINGH'));

III. Display the list of all teachers who take classes for batch ‘B004’ SQL> SELECT TNAME FROM TEACHERS WHERE

BATCHID='B004';

IV. Display the name of teachers who were working in regional centre ‘BBSR’ SQL> SELECT TNAME FROM TEACHERS WHERE

BATCHID IN(SELECT BATCHID FROM BATCH WHERE

RCID=(SELECT RCID FROM REGCENT WHERE RCNAME='BBSR'));

V. Display the name of students who are representative student. SQL> SELECT NAME FROM STUDENT WHERE STDID IN

(SELECT REPSTDID FROM BATCH);

VI. Display the name of teachers who teach in delhi and have atleast two ‘a’ in their name. SELECT TNAME FROM TEACHERS WHERE

UPPER(TNAME) LIKE '%A%A%'

AND

BATCHID IN(SELECT BATCHID FROM BATCH WHERE

RCID=(SELECT RCID FROM REGCENT WHERE

UPPER(RCNAME)='NDLS'));

VII. Display the name of student whose teachers name starts with ‘S’. SELECT NAME FROM STUDENT WHERE

BATCHID IN (SELECT BATCHID FROM BATCH WHERE

BATCHID IN (SELECT BATCHID FROM TEACHERS WHERE

UPPER(TNAME) LIKE 'S%'));

VIII. Display the name of the teachers with the batch details. SELECT TNAME,B.BATCHID,RCID,SDYID,COURSEID,REPSTDID

* FROM TEACHERS T,BATCH B WHERE B.BATCHID=T.BATCHID

IX. Display the name of students along with course details. SELECT NAME,C.COURSEID,COURSENAME,COURSEFEE FROM STUDENT S, COURSE C,

BATCH B WHERE

S.BATCHID=B.BATCHID

AND

* B.COURSEID=C.COURSEID;

X. Display the teachers name along with the students they teach. SQL> SELECT TNAME,NAME FROM TEACHERS T,STUDENT S

WHERE T.BATCHID=S.BATCHID;

XI. Display course and study centers that offer them. SELECT COURSENAME,SDYNAME FROM COURSE C,SDYCENT S,BATCH B

WHERE

B.SDYID=S.SDYID

AND

* B.COURSEID=C.COURSEID;

XII. Display students name who read under teacher whose last name is ‘sehgal’. SELECT NAME FROM STUDENT WHERE BATCHID IN(

SELECT BATCHID FROM TEACHERS WHERE

* UPPER(TNAME) LIKE '%SEHGAL%');

XIII. Display students and related regional centres. SQL> SELECT NAME, RCNAME FROM STUDENT S,REGCENT R,BATCH B

WHERE

R.RCID=B.RCID

AND

S.BATCHID=B.BATCHID;

XIV. Display STUDENTID of students and techersid. SQL> SELECT STDID,TCHID FROM STUDENT S, TEACHERS T

WHERE S.BATCHID=T.BATCHID;

XV. Display student, teacher and rc. SQL> SELECT NAME,TNAME,RCNAME FROM STUDENT S,TEACHERS T,REGCENT R,BATCH B

WHERE

S.BATCHID=T.BATCHID

AND

T.BATCHID=B.BATCHID

AND

B.RCID=R.RCID;

Page 17: MCSL-045 Lab Manual

Ex 3: Design a suitable database system for a bank along with 20 possible queries to the database (the

queries should be such that their solution involves sub queries or joins or both). Implement the database

and the queries in a commercial DBMS using SQL.

Ans: Bank database :

create table acco_master (accno number(10) primary key,name * varchar2(10),balance number(10))

SQL>

insert into acco_master values(&accno,'&name',&balance)

Enter value for accno:111

Enter value for name:faraz

Enter value for balance:200000

SQL>

create table acco_trans(accno number(10),trans_date date,deb_cre

varchar2(10),check(deb_cre IN('debit','credit')),amount number(10), process varchar2(10)

check(process IN('yes','no')) foreign key (accno)references acco_master);

SQL> insert into acco_trans values(&accno,'sysdate,'&deb_cre',&amount, '&process');

Enter value for accno:111

Enter value for deb_cre:debit

Enter value for amount:1000

Enter value for process:yes

Session 2 : Creating Views, Indexes and Queries on Them

Ex 1 : Please attempt the following problems for the teacher, class and payscale relations given in this section.

(a) Create a view named ‘supervisor_details’ that stores the names and numbers of all the supervisors.

Ans: create view supervisor_detail as

select f_name ||' '|| l_name as name from teacher where title='supervisor';

select * from supervisor_detail

(b) Create a non-unique index on the foreign key column of the ‘class’ table.

Ans: CREATE INDEX SCOTT.class_index ON SCOTT.CLASS

(CLASS_NO)

LOGGING

NOPARALLEL;

(c) Modify the view created in (a) and add details like salary, job title, joining date, birth date etc. of all

supervisors.

Ans: CREATE OR REPLACE VIEW SCOTT.SUPERVISOR_DETAIL

(NAME,salary,jobtitle,birthdate)

AS

SELECT f_name || ' ' || l_name AS NAME ,salary as salary ,title as jobtitle , birthdate as birthdate

FROM teacher

WHERE title = 'supervisor';

(d) Using the view created in (c) display details of all supervisors who have worked for more than 15 years.

Ans: select * from supervisor_detail where to_char(sysdate,'yyyy')- to_char(joiningdate,'yyyy') >=15

(e) Create a view that stores the details of all the teachers who are TGT and earning more than Rs.12000/-.

Ans: CREATE OR REPLACE VIEW SCOTT.TECHER_DETAIL

AS

SELECT * FROM teacher

WHERE title = 'TGT' and salary>12000 ;

(f) Drop the view created in (e).

Ans: drop view SCOTT.TECHER_DETAIL

(g) Create a non-unique index on the names of teachers in the ‘teachers’ table.

Ans: create index t_name_index on teacher(f_name)

(h) Drop the index created in (b).

Ans: drop index CLASS_INDEX

(i) Create a view named ‘teacher_info’ that only allows users to view the teacher id, name, salary and grade

of the teachers. It should not allow any user to change/update any information.

Ans: create view teacher_info as

select t_no, f_name ||' '|| l_name as Name, salary from teacher;

View created.

SQL> select * from teacher_info;

Granting permissions

SQL> grant select

Page 18: MCSL-045 Lab Manual

on teacher_info

to system;

Grant succeeded.

(j) Create a view that displays details of all teachers who are in grade ‘B’ and are more than 40 years old. Ans: CREATE OR REPLACE VIEW SCOTT.TECHER_DETAIL1

AS

SELECT t_no ,f_name||' '||l_name as name,title,salary,

trunc(months_between(sysdate,birthdate)/12,0) age , grade from teacher, payscale

WHERE salary between min_limit and max_limit ;

select * from TECHER_DETAIL1 where age>40

Ex 2 : Design suitable views for the University database system (Exercise 1, question 2). For example, you

can create a view for the faculty giving him/her details of his/her students. Create at least 5 suitable queries

on each of the views created by you. Also create indexes for the University database system. For example,

you can create an index on student name, thus, allowing faster access to student information in the order of

student names. You must explain how the indexes created by you would enhance the performance of the

database system. Implement the above in a commercial DBMS using SQL.

Ans:

Ex 3 : Design suitable views and indexes for the Bank database system (Exercise 1, question 3). Create at

least 5 suitable queries on each of the views. Explain how the indexes created by you would enhance the

performance of the database system. Implement the above in a commercial DBMS using SQL.

Ans:

Session 3 : PL/SQL – Control Loops and Procedures

Ex 1: Please perform the following using the following relations:

Teacher(t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, title)

Class(class_no, t_no, room_no)

Payscale(Min_limit, Max_limit, grade)

(a) Calculate the bonus amount to be given to a teacher depending on the following conditions:

I. if salary > 10000 then bonus is 10% of the salary.

II. if salary is between 10000 and 20000 then bonus is 20% of the salary.

III. if salary is between 20000 and 25000 then bonus is 25% of the salary.

IV. if salary exceeds 25000 then bonus is 30% of the salary.

Ans: CREATE OR REPLACE PROCEDURE Calculate_Bonus(t_no in int) IS

Vbonus int;

Vtno int :=0;

Vsal int :=0;

BEGIN

Vbonus :=0;

Vtno :=t_no;

select salary into Vsal from teacher1 where t_no=Vtno;

if(Vsal<10000) then

Vbonus :=Vsal*(10/100);

elsif(Vsal between 10000 and 20000) then

Vbonus :=Vsal*(20/100);

elsif(Vsal between 20000 and 25000) then

Vbonus :=Vsal*(25/100);

elsif(Vsal >25000) then

Vbonus :=Vsal*(30/100);

end if;

dbms_output.put_line(Vbonus);

-- bonus :=Vbonus;

END Calculate_Bonus;

(b) Using a simple LOOP structure, list the first 10 records of the ‘teachers’ table.

Ans: declare

fetchten teacher%rowtype;

cnt number :=0;

cursor curr

is

select * from teacher;

begin

open curr;

loop

exit when curr%notfound or cnt=10;

fetch curr into fetchten;

Page 19: MCSL-045 Lab Manual

dbms_output.put_line(fetchten.t_no||' '||fetchten.f_name||' '||fetchten.l_name);

cnt :=cnt+1;

end loop;

close curr;

end;

(c) Create a procedure that selects all teachers who get a salary of Rs.20, 000 and if less than 5 teachers are

getting Rs.20, 000 then give an increment of 5%.

Ans: declare

fetchten teacher%rowtype;

cnt number :=0;

cursor curr

is

select * from teacher;

begin

open curr;

loop

exit when curr%notfound ;

fetch curr into fetchten;

if fetchten.salary>20000 then

dbms_output.put_line(fetchten.t_no||' '||fetchten.f_name||' '||fetchten.l_name);

else

cnt :=cnt+1;

end if;

end loop;

if cnt<5 then

update teacher set salary=salary*1.05 where salary<20000;

dbms_output.put_line('Updated salary');

end if;

close curr;

end;

(d) Create a procedure that finds whether a teacher given by user exists or not and if not then display

“teacher id not exists”.

Ans: create or replace procedure findteacher(teach in varchar2)

is

c_t_no teacher.t_no%type;

cnt number :=0;

cursor curr is

select t_no from teacher where f_name=teach;

begin

open curr;

fetch curr into c_t_no;

if curr%notfound then

dbms_output.put_line('The teacher you enquired does not exist');

else

dbms_output.put_line('The teachers id you enquired is '||c_t_no);

end if;

close curr;

end;

(e) Using FOR loop, display name and id of all those teachers who are more than 58 years old.

Ans: create or replace procedure ShowAboveF8

is

C_F_NAME Teacher.F_NAME%Type;

C_L_NAME Teacher.L_NAME%Type;

begin

select F_NAME,L_NAME into C_F_NAME,C_L_NAME from teacher where

months_between(sysdate,birthdat DBMS_OUTPUT.PUT_LINE(C_F_NAME||'

'||C_L_NAME);

* end;

(f) Using while loop, display details of all those teachers who are in grade ‘A’.

Ans:

(g) Create a procedure that displays the names of all those teachers whose supervisor is ‘Suman’.

Ans: create or replace procedure StaffUnder(superv in varchar2) is

temphold teacher%rowtype;

cursor curr is

select * from teacher where supervisor=superv;

Page 20: MCSL-045 Lab Manual

begin

open curr;

loop

fetch curr into temphold;

exit when curr%notfound;

dbms_output.put_line(temphold.F_name);

end loop;

close curr;

end;

(h) Calculate the tax to be paid by all teachers depending on following conditions:

I. if annual salary > 1,00,000 then no tax.

II. if annual salary is between 1,00,001 and 1,50,000 then tax is 20% of the annual salary.

III. if annual salary is between 1,50,001 and 2,50,000 then tax is 30% of the annual salary.

IV. if salary exceeds 2,50,000 then tax is 40% of the annual salary.

Ans: create or replace procedure TaxCalc

is

t_F_Name teacher.F_Name%type;

t_Salary teacher.Salary%type;

tax teacher.Salary%type;

cursor curr is

select F_name,Salary*12 from teacher;

begin

open curr;

loop

fetch Curr into t_F_name,t_Salary ;

exit when curr%notfound;

if t_Salary<100000 then

tax:=0;

elsif t_Salary<150000 then

tax:=(t_Salary-100000)*0.20;

elsif t_Salary<250000 then

tax:=(t_Salary-150000)*0.30+50000*0.20;

else

tax:=(t_Salary-250000)*0.40+100000*0.30+50000*0.20;

end if;

DBMS_OUTPUT.PUT_LINE(t_F_NAME||' OWES '||tax||' as Tax ');

end loop;

close curr;

end;

(i) Create a procedure that finds the names of all teachers with the job title ‘PRT’ and if the number of

teachers returned is more than 10 than change the job title to ‘TGT’ for the top 3 ‘PRT’ teachers based on

their hiredate.

Ans: CREATE OR REPLACE PROCEDURE CheckTGTExceed IS

Vcount int ;

Vmaxdate date ;

BEGIN

loop

select count(*) into Vcount from teacher1 where title='TGT' ;

select max(joiningdate) into Vmaxdate from teacher1 where title='TGT';

if(Vcount>2) then

update teacher1 set title='PRT' where joiningdate=Vmaxdate and title='TGT';

else

exit;

end if;

end loop;

END CheckTGTExceed;

Ex 2: Identify the need of procedures for the University database system; for example, you can create a

procedure that awards 2% grace marks for those students who have got 48% marks. Design at least 5 such

procedures. Implement these procedures using an embedded SQL.

Ans:

Ex 3: Implement at least five procedures for the Bank Database system using embedded SQL.

Ans: SQL>set serveroutput on

SQL>declare

cursor c_bank is select * from acco_trans;

v_bank c_bank%rowtype;

balance number(5);

begin

Page 21: MCSL-045 Lab Manual

open c_bank;

loop

fetch c_bank into v_bank;

exit when c_bank%notfound;

if v_bank.process='no' then

update acco_trans set process='yes' where

accno=v_bank.accno;

if v_bank .deb_cre='credit' then

update acco_master set balance=balance+v_bank.amount

where v_bank.accno=acco_master.accno;

elsif v_bank.deb_cre='debit' then

update acco_master set balance=balance-v_bank.amount

where v_bank.accno=acco_master.accno;

elsif balance<=0 then

dbms_output.put_line('Transaction not possible');

end if;

end if;

end loop;

close c_bank;

end;

SQL>select * from acco_trans;

AccNo Trans_Date Deb_Cre Amt Pro

---------- -------------- ------------ --------- --------------

1012 12-Jan-08 debit 5000 yes

1024 14-Feb-08 credit 100 yes

1987 04-Dec-07 credit 1000 yes

2345 17-Mar-08 credit 20000 yes

Cursor for BANK DATABASE

SQL > create table depositor (accno primary key , cname char(10))

Table created.

SQL > create table borrower (loanno number , cname char(10))

Table created.

SQL > create table loan( loanno number , brname char(10),amt number)

Table created.

SQL > create table acct-t( acctno number , bal number, brname char(10), foreign key (acctno)

references depositor (acctno)

Table created.

SQL > insert into depositor values (&accno , &cname );

Enter value for accno : 101

Enter the value for cname : Alan

SQL > insert into acct-t values( &acctno , &bal , '&brname ');

Enter value for accno : 101

Enter the value for bal : 20000

Enter the value for brname : tvm

SQL > select * from depositor;

ACCNO CNAME

101 Alan

102 Ann

103 Ben

SQL > select * from acct-t;

ACCNO BAL BRNAME

------------- ------------------- ----------------

101 20000 tvm

102 10500 ekm

103 5000 tcr

SQL > create or replace trigger

declare

c varchar2 (20)

begin

if (:new.bal < :old.bal) then

insert into loan values (:new.accno, :new.brname , :old.bal-:new.bal);

select cname into c from depositor where accno = new.accno;

insert into borrower values (:new.accno,c);

endif;

end;

Trigger created.

SQL > update acct-t set bal = bal-5000 where acctno=101

1 row updated.

SQL >select * from borrower;

LOANNO CNAME

-------------- --------------------

Page 22: MCSL-045 Lab Manual

101 Alan

SQL >select * from loan;

LOANNO BR NAME AMT

101 tvm 15000

Session 4 : Cursors

Ex 1: Please perform the following using the following relations:

Teacher(t_no, f_name, l_name, salary, supervisor, joiningdate, birthdate, title)

Class(class_no, t_no, room_no)

Payscale(Min_limit, Max_limit, grade)

(a) Create a host language block to declare a cursor for displaying teacher numbers and their names for all

teachers having title ‘PGT’.

Ans: ed

Wrote file afiedt.buf

CREATE OR REPLACE PROCEDURE E4a IS

vno int ;

Vname varchar2(30);

Vrec varchar2(100);

cursor c1 is select T_NO,F_NAME from teacher where TITLE='TGT';

BEGIN

--vno :=0;

--Vname :='';

Vrec :='';

open c1;

loop

exit when c1%notfound;

fetch c1 into vno,Vname;

Vrec :=vno ||' '|| Vname;

dbms_output.put_line(Vrec);

end loop;

close c1;

END E4a * ;

Procedure created.

SQL> exec e4a

6 Jatin

6 BBB

6 BBB

PL/SQL procedure successfully completed.

(b) Create a host language block using a cursor to calculate bonus for teachers as 5% of their salary.

Display on screen the teacher details along with the bonus given.

Ans: declare

vno int ;

Vname varchar2(30);

bonus int ;

cursor c1 is select F_NAME,salary from teacher;

begin

vno :=0;

Vname :='';

open c1;

dbms_output.put_line('Name Bonus');

dbms_output.put_line('-------------');

loop

exit when c1%notfound;

fetch c1 into Vname,vno;

bonus :=vno*(5/100);

-- dbms_output.put_line(vno||Vname);

dbms_output.put_line(Vname||', bonus: '||bonus);

end loop;

close c1;

* end;

(c) Write a host language block to delete all the rows from the ‘teacher’ table where the salary is less than

Rs.5000.

Ans: DECLARE

c_t_no teacher.t_no%TYPE;

c_f_name teacher.f_name%TYPE;

c_l_name teacher.l_name%TYPE;

c_salary teacher.salary%TYPE;

CURSOR c1 IS

Page 23: MCSL-045 Lab Manual

SELECT t_no,f_name, l_name, salary

FROM teacher;

BEGIN

OPEN c1;

LOOP

FETCH c1 INTO c_t_no, c_f_name, c_l_name, c_salary ;

EXIT WHEN NOT c1%FOUND;

UPDATE teacher SET salary = salary * 1.10 WHERE salary < 5000;

END LOOP;

CLOSE c1;

END;

(d) Write a host language code to insert the supervisor information from ‘teacher’ table to another table

called ‘supervisor’. The new table should have only those records where the job title is ‘supervisor’.

Ans: DECLARE

CURSOR c2 IS

SELECT t_no,f_name, l_name, salary

FROM teacher ;

teacher_rec c2%ROWTYPE;

BEGIN

OPEN c2;

FOR teacher_rec IN c2

LOOP

I F teacher_rec.salary > 20000

Teacher_rec.title = “SUPERVISOR”;

ENDIF;

END LOOP;

CLOSE c2;

END;

(e) Write a block in host language that deletes all the rows from ‘teacher’ table if the teacher was hired for

more than 10 years.

Ans: declare

vno int ;

Vname varchar2(30);

bonus int ;

cursor c1 is select T_NO,F_NAME from teacher

where trunc(months_between(sysdate,JOININGDATE) /12,0)>10;

begin

vno :=0;

Vname :='';

open c1;

loop

exit when c1%notfound;

fetch c1 into vno,Vname;

delete from teacher where T_NO =vno;

dbms_output.put_line('Delete'||vno);

end loop;

close c1;

end;

(f) Write a block in host language using cursor that displays the names of all teachers who will attain the

age of 60 years in the current year.

Ans: declare

vno int ;

Vname varchar2(30);

bonus int ;

cursor c1 is select T_NO,F_NAME from teacher

where runc(months_between(sysdate,BIRTHDATE)/12,0)>45;

begin

vno :=0;

Vname :='';

open c1;

loop

exit when c1%notfound;

fetch c1 into vno,Vname;

-- delete from teacher1 where T_NO =vno;

dbms_output.put_line('name :'||Vname);

end loop;

Page 24: MCSL-045 Lab Manual

close c1;

end;

(g) Write a block in host language using cursors that display teacher details along with the tax to be paid by

that teacher. The tax is calculated depending on following conditions:

I. if annual salary 1,00,000 then no tax.

II. if annual salary is between 1,00,001 and 1,50,000 then tax is 20% of the annual salary.

III. if annual salary is between 1,50,001 and 2,50,000 then tax is 30% of the annual salary.

IV. if salary exceeds 2,50,000 then tax is 40% of the annual salary.

Ans: CREATE OR REPLACE PROCEDURE E4g(tid in int) IS

Vid int ;

Vmsal int ;

Vysal int;

tax int ;

Vtsal int ;

cursor c1 is select salary from teacher where t_no=tid;

BEGIN

open c1 ;

loop

exit when c1%notfound;

fetch c1 into Vtsal;

Vysal :=Vtsal*12;

if(Vysal<100000) then

dbms_output.put_line('no tax');

elsif(Vysal between 100001 and 150000) then

tax := Vysal*(20/100);

elsif(Vysal between 150001 and 250000) then

tax := Vysal*(30/100);

elsif(Vysal>250000) then

tax := Vysal*(40/100);

end if;

end loop;

dbms_output.put_line(tax);

close c1;

END E4g;

(h) Write a block in host language that displays the details of all those teachers who have reached

maximum limit of their grade.

Ans: CREATE OR REPLACE PROCEDURE E4h IS

vno int ;

Vfname varchar2(30);

Vlname varchar2(30);

Vsalary int;

Vsup varchar2(30);

Vjdate date;

Vbdate date ;

Vtitle varchar2(30);

cursor c1 is select

T_NO,F_NAME,L_NAME,SALARY,SUPERVISOR,JOININGDATE,BIRTHDATE,TITLE from

teacher1,payscale WHERE salary= max_limit ;

BEGIN

open c1;

loop

exit when c1%notfound;

fetch c1 into vno,Vfname,Vlname,Vsalary,Vsup,Vjdate,Vbdate,Vtitle;

dbms_output.put_line('T_no'||vno||' '

||Vfname||Vlname||Vsalary||Vsup||Vjdate||Vbdate||Vtitle);

end loop;

close c1;

END E4h;

----------------------------or---------------------------

SELECT distinct( grade), max(salary),title

from teacher1,payscale

WHERE salary= max_limit

group by salary,title,grade

Ex 2: Write at least four embedded SQL blocks having cursors for the University database system; for

example, you can create a cursor to update the examination marks of a student that are given in a list to the

student’s database. Implement these procedures using an embedded SQL.

Page 25: MCSL-045 Lab Manual

Ans:

Ex 3: Implement at least five embedded SQL blocks having cursors for the Bank Database system.

Ans:

Session 5 : Error Handling And Transaction Management

Ex 1: Write an embedded SQL block along with exceptions to select the name of the teacher with a given

salary. If more than one row is returned than display more than one row retrieved. If no row is returned

then display ‘no teacher with this salary’.

Ans: CREATE OR REPLACE PROCEDURE E5a(tid in int) IS

Vsal int;

Vfname varchar2(30);

Vrc int ;

BEGIN

select f_name, salary,count(*)as sasa into Vfname,Vsal,Vrc from teacher where t_no=tid group

by f_name,salary;

if(Vrc>=1) then

dbms_output.put_line('recoed found');

else

dbms_output.put_line('recoed not found');

end if;

EXCEPTION

when no_data_found then

raise_application_error(-20100,'not tid found enter the valid teacher id ') ;

dbms_output.put_line('envalid teacher id ');

WHEN NO_DATA_FOUND THEN

NULL;

WHEN OTHERS THEN

Consider logging the error and then re-raise

RAISE;

END E5a;

Ex 2: Create a program that updates a record into the ‘teacher’ table. Trap and handle the exception if the

teacher id is not available in the ‘teacher’ table.

Ans: create or replace procedure UpdateSal(TeacherName in VARCHAR2)

is

cnt Number:=0;

tF_name teacher.F_Name%Type;

NoTeacherFound Exception;

Cursor curr

is

select salary from teacher where f_name=TeacherName;

BEGIN

open curr;

loop

fetch curr into tF_Name;

exit when curr%notfound;

cnt:=cnt+1;

end loop;

close curr;

if cnt<1 then

RAISE NoTeacherFound;

else

update teacher set salary=1.05*salary where F_Name=TeacherName;

end if;

EXCEPTION

When NoTeacherFound then

RAISE_APPLICATION_ERROR('-20003','No Teacher with this Name');

end;

Ex 3: Write a program with exceptions that displays the details of all those teachers who have reached

maximum limit of their grade. If no row is retrieved then raise the exception “no teacher reached max limit

of grade”.

Ans:

Ex 4: Insert at least 5 new rows in the ‘teacher’ table and then try to rollback last 3 rows inserted to the

table. (Here, you are required to use save points).

Page 26: MCSL-045 Lab Manual

Ans:

Ex 5: Write a program with exceptions that displays the names of all teachers who will attain the age of 60

years in the current year. If no row is retrieved than display suitable exception.

Ans:

Ex 6: Write a PL/SQL block that displays all the rows from ‘teacher’ table if the teacher was hired for

more than 10 years and still a ‘PRT’. If no result than display suitable message.

Ans:

Ex 7: In all the embedded SQL program segments that you have created so far for the University and

Bank database system, create suitable error handling features.

Ans:

Ex 8: Experiment with DDL and DML commands along with COMMIT and ROLLBACK for the

Teacher, University and Banking databases.

Ans:

Session 6 : Triggers And Functions

Ex 1: Write a trigger that is fired before the DML statement’s execution on the TEACHER table. The

trigger checks the school timings based on SYSDATE. Beyond the School working hours the trigger raises

an exception, which does not allow any work to be happened.

Ans: create or replace trigger Q1

before insert or update or delete on teacher

for each row

when (to_char (SYSDATE,'HH24') between 9 and 23)

begin

dbms_output.put_line('Cant Do any job outside school timings');

end;

Ex 2: Write a trigger that is fired before an UPDATE statement is executed for the teacher table. The

trigger should write the name of teacher, user name and system date in an already created table called

UPDATE_TABLE.

Ans: CREATE TABLE UPDATE_TABLE( TEACHER_NAME VARCHAR2(20),USER_NAME VARCHAR2(20)

DEFAULT 'STUDENT', SYS_DATE DATE);

CREATE OR REPLACE TRIGGER :

BEFORE UPDATE ON TEACHER

FOR EACH ROW

DECLARE

BEGIN

INSERT INTO UPDATE_TABLE VALUES(:OLD.F_NAME,USER,SYSDATE);

END;

RESULTANT TABLE:

Jaideep ANONYMOUS 07-JAN-08

Parag ANONYMOUS 07-JAN-08

ON EXECUTING:

UPDATE TEACHER SET F_NAME=’A’ WHERE F_NAME=’Parag’;

UPDATE TEACHER SET L_NAME=’A’ WHERE L_NAME=’Patel’;

Ex 3: Write a trigger that is fired before any row is inserted in the ‘teacher’ table.

Ans: BEFORE UPDATE ON TEACHER

BEGIN

IF UPDATING THEN

DBMS_OUTPUT.PUT_LINE('YOU ARE GOING TO UPDATE THE TEACHER TABLE');

END IF;

END;

Ex 4: Write a function and pass a job title to it. If the TEACHER table does not contain any row

corresponding to that title then return false otherwise true.

Page 27: MCSL-045 Lab Manual

Ans: create or replace function chk_fuct(f_title in varchar(20))

is

ff_name varchar(20);

cnt int;

begin

select f_name, count(*) into ff_name,cnt from teacher

where title=f_title;

if (cnt>=1) then

return 'Sucess';

else

return 'Not Sucess';

end if;

end chk_fuct;

Ex 5: Write a trigger that verifies the joining date when a new row is inserted in the ‘teacher’ table.

Joining date should be greater or equal to current date.

Ans: ed

Wrote file afiedt.buf

create trigger e6_5

after insert on teacher

for each row

Declare

jdate teacher.joiningdate%TYPE;

cdate date;

begin

jdate:=new.joiningdate;

cdate:=sysdate;

if jdate>=cdate then

dbms_output.put_line('Joining date is fine');

commit;

else

rollback;

end if;

end;

Ex 6: Write a function that gets the teacher id as parameter and returns the class number associated with

that teacher. If the teacher is not a class teacher then give suitable message.

Ans: DECLARE

C_id teacher.t_no%TYPE; C_f_name teacher.f_name%TYPE; want_id NUMBER := 110; BEGIN

SELECT t_no, f_name INTO c_t_no, c_f_name from teacher WHERE t_no = want_id; DBMS_OUTPUT.PUTLINE ( “teacher : “|| c_t_no ||’ ‘||c_f_name) EXCEPTION WHEN INVALID_NUMBER THEN DBMS_OUTPUT.PUTLINE(want_id || ‘ not a valid teacher id’);

END; CREATE OR REPLACE TRIGGER new_teacher _id AFTER INSERT ON teacher FOR EACH ROW DECLARE o_t_no teacher.t_no%TYPE; o_joiningdate teacher.joiningdate%TYPE; BEGIN

SELECT t_no_sequence.nextval INTO o_t_no FROM dual; :NEW.t_no := o_t_no; :NEW.joiningdate := SYSDATE;

END;

Ex 7: Write a function and pass a teacher id to it. If the TEACHER table does not contain that id then

return false otherwise true.

Ans:

Ex 8: Write a function that takes teacher id as parameter and returns back the name and joining date of

the teacher.

Ans:

Page 28: MCSL-045 Lab Manual

Ex 9: Write appropriate triggers and functions for the University and Bank database systems.

Ans: Create or replace trigger e6_9

After insert on teacher on univ

For each row

begin

Dbms_output.put_line(‘data inserted sucessfully’);

end

Session 7 : Creating Object Types / Tables

Ex 1: Assuming that in the teacher relation an attribute of object type called dependent is added. Make

dependent a type that may consist of only one dependent. Add few records in the tables and output them

using a query on teacher name. Find if you can search on a dependent name.

Ans: SQL> create type dependent as object

(

name varchar(20)

);

Type created.

SQL> ed

Wrote file afiedt.buf

create table teacher(

t_no int,

f_name varchar(30),

l_name varchar(30),

salary int,

supervisor varchar(50),

joiningdate date,

birthdate date,

title varchar(50)

d_name dependent

* )

Table created.

SQL> Insert into teacher values(

(10101, ‘MP’, ‘Joshi’, 30000, ‘Mohan’, ’10-dec-08’, ’10-feb-07’, ‘TGT’,

Dependent(‘sita’)

);

1 row created.

Ex 2: Create at least two object types in both the University and Bank database systems. Use these object

types in few relations and enter some data into these relations. Query these databases.

Ans: SQL> ed

Wrote file afiedt.buf

create type type4univ as object

(

name varchar(20),

phone number(10)

* );

Type created.

SQL> create type type4bank as object

(

branch varchar(20),

manager varchar(20)

);

Type created.

Session 8 : Nested Tables

Ex 1: Add a nested table in the teacher relation. Do some queries using nested tables?

Ans:

Page 29: MCSL-045 Lab Manual

CREATE TABLE student_credits

(rollno NUMBER(5), s_name VARCHAR2(25), subject_credits NEW_TYPE)

NESTED TABLE subject_credits STORE AS new_type_table;

INSERT INTO student_credits

VALUES (100, ‘suman’ , new_table ( new_type (‘english’ , 30), new_table ( new_type(‘hindi’, 35)));

SELECT s.credit_hours FROM

THE (SELECT subjects_credit FROM student_credits WHERE s_name = ‘suman’) s

WHERE s.subject_name = ‘english’;

Ex 2: Create at least two nested tables for both the University and Bank database systems. Use these tables

and enter some data into these relations. Query these databases.

Ans: CREATE TYPE address_t AS OBJECT ( street VARCHAR2(30), city VARCHAR2(20), state CHAR(2), zip CHAR(5) ); / CREATE TYPE address_tab IS TABLE OF address_t; / CREATE TABLE customers ( custid NUMBER, address address_tab ) NESTED TABLE address STORE AS customer_addresses; INSERT INTO customers VALUES (1, address_tab( address_t('101 First', 'Redwood Shores', 'CA', '94065'), address_t('123 Maple', 'Mill Valley', 'CA', '90952') ) );

Session 9 : Storing Blobs

Ex 1: Identify the use of large object types in the teacher’s table. Do some queries using these objects.

Ans: CREATE TABLE message ( msg_id NUMBER(8) NOT NULL PRIMARY KEY, email_add VARCHAR(200), name VARCHAR (200), message CLOB, posting_time DATE, sort_key VARCHAR (600)); DECLARE Image10 BLOB; image_number INTEGER := 101; BEGIN SELECT item_blob INTO image10 FROM lob_table10 WHERE key_value = image_number; DBMS_OUTPUT.PUT_LINE('Image size is:'||DBMS_LOB.GETLENGTH(image10)); END;

Ex 2: Create at least two large objects for both the University and Bank database systems. Enter some data

into these relations. Query these databases.

Ans: SQL> ed

Wrote file afiedt.buf

declare

image10 blob;

image_no integer:=101;

begin

select item_blob into image10 from universities

where t_no=Image_no;

dbms_output.put_line('Image size is:'||dbms_lob.getLength(image10);

end;

SQL> ed

Wrote file afiedt.buf

declare

image11 blob;

image_num integer:=01;

begin

select item_blob into image11 from Bank

where b_no=Image_num;

Page 30: MCSL-045 Lab Manual

dbms_output.put_line('Image size is:'||dbms_lob.getLength(image11);

end;

Session 10 : User Management and Object Privileges

Ex 1: Create a user account “class” and give privileges related to table/view creation, deletion, updating

and dropping.

Ans: CREATE USER class

IDENTIFIED BY pass;

GRANT CREATE TABLE, DROP TABLE, CREATE VIEW, DROP VIEW

TO class;

Ex 2: Create a student account and give permission to this account for only viewing the information on the

relation Class (class_no, t_no, room_no).

Ans: DENY UPDATE, DELETE, INSERT ON employee TO student GO CREATE USER student @Eclass_no int, @St_no money, @room_no int GRANT EXECUTE ON student TO Class GO

Ex 3: Create at least 3 to 4 different types of users for each of the database systems:

University and Bank. Design suitable access privileges for the users. Grant these permissions to the users.

Ans: SQL> create user Murali identified by mpjoshi;

User created.

SQL> create user biku identified by deepak;

User created.

SQL> create user samir identified by rajak;

User created.

SQL> create user prashant identified by jain;

User created.

Creating access privileges:

t select, insert, update to Murali

grant options;

Grant succeeded.

t select, insert, update to biku

grant options;

Grant succeeded.

t select, insert, update to samir

grant options;

Grant succeeded.

t select, insert, update to prashant

grant options;

Grant succeeded.

Ex 4: Consider when you have a large number of students and teachers in the University databases that

have different access rights. Is there any mechanism in DBMS that allows defining an account type to some

specific role? If yes, then define such types for the University database system.

Ans:

Ex 5: Define different types of users for the Bank database and provide them suitable access rights.

Ans: User Creation:

create user Manager identified by mgr1;

User created.

create user cashier identified by cash1;

User created.

create user clerk identified by clrk1;

Page 31: MCSL-045 Lab Manual

User created.

create user General_manager identified by gm;

User created.

User rights assignments:

grant create table, update table,

drop table, create view, update view,

drop view to General_manager;

Grant succeeded.

grant create table, update table,

drop table, create view, update view,

drop view to Manager;

Grant succeeded.

grant update table,

create view, update view, to class;

Grant succeeded.

grant , update table,

drop table, , update view,to Clerk;

Grant succeeded.