Вы находитесь на странице: 1из 70

PRACTICAL-1

database.

Install and configure MySQL

MySQL is a freely available open source Relational Database Management System (RDBMS) that
uses Structured Query Language (SQL).

MySQL is a database management system.


A database is a structured collection of data. It may be anything from a simple shopping list to a
picture gallery or the vast amounts of information in a corporate network. To add, access, and
process data stored in a computer database, you need a database management system such as
MySQL Server. Since computers are very good at handling large amounts of data, database
management systems play a central role in computing, as standalone utilities, or as parts of other
applications.

MySQL databases are relational.


A relational database stores data in separate tables rather than putting all the data in one big
storeroom. The database structures are organized into physical files optimized for speed. The
logical model, with objects such as databases, tables, views, rows, and columns, offers a flexible
programming environment. You set up rules governing the relationships between different data
fields, such as one-to-one, one-to-many, unique, required or optional, and pointers between
different tables. The database enforces these rules, so that with a well-designed database, your
application never sees inconsistent, duplicate, orphan, out-of-date, or missing data.
The SQL part of MySQL stands for Structured Query Language. SQL is the most common
standardized language used to access databases. Depending on your programming
environment, you might enter SQL directly (for example, to generate reports), embed SQL
statements into code written in another language, or use a language-specific API that hides the
SQL syntax.
SQL is defined by the ANSI/ISO SQL Standard. The SQL standard has been evolving since 1986
and several versions exist. In this manual, SQL-92 refers to the standard released in
1992, SQL:1999 refers to the standard released in 1999, and SQL:2003 refers to the current
version of the standard. We use the phrase the SQL standard to mean the current version of the
SQL Standard at any time.

MySQL software is Open Source.


Open Source means that it is possible for anyone to use and modify the software. Anybody can
download the MySQL software from the Internet and use it without paying anything. If you wish,
you may study the source code and change it to suit your needs. The MySQL software uses the
GPL (GNU General Public License), to define what you may and may not do with the software in
different situations. If you feel uncomfortable with the GPL or need to embed MySQL code into a
commercial application, you can buy a commercially licensed version from us. See the MySQL
Licensing Overview for more information

The MySQL Database Server is very fast, reliable, scalable, and easy to use.
If that is what you are looking for, you should give it a try. MySQL Server can run comfortably on
a desktop or laptop, alongside your other applications, web servers, and so on, requiring little or
no attention. If you dedicate an entire machine to MySQL, you can adjust the settings to take
advantage of all the memory, CPU power, and I/O capacity available. MySQL can also scale up
to clusters of machines, networked together.
You can find a performance comparison of MySQL Server with other database managers on our
benchmark page.
MySQL Server was originally developed to handle large databases much faster than existing
solutions and has been successfully used in highly demanding production environments for
several years. Although under constant development, MySQL Server today offers a rich and
useful set of functions. Its connectivity, speed, and security make MySQL Server highly suited for
accessing databases on the Internet.

MySQL Server works in client/server or embedded systems.


The MySQL Database Software is a client/server system that consists of a multi-threaded SQL
server that supports different backends, several different client programs and libraries,
administrative tools, and a wide range of application programming interfaces (APIs).
We also provide MySQL Server as an embedded multi-threaded library that you can link into your
application to get a smaller, faster, easier-to-manage standalone product.

A large amount of contributed MySQL software is available.


MySQL Server has a practical set of features developed in close cooperation with our users. It is
very likely that your favorite application or language supports the MySQL Database Server.

Follow the instructions below exactly when installing MySQL Server:

Click on the "setup"

Perform a typical installation

<!--[if !vml]--><!--[endif]-->

Check box to configure MySQL Server


If you checked the Configure the MySQL Server now check box on the final dialog of the MySQL
Server installation, then the MySQL Server Instance Configuration Wizard will automatically start.
Follow the instructions below carefully to configure your MySQL Server to run correctly with
EventSentry.

Select Detailed Configuration

I was installing it on my local machine where other applications & tools are running I decided to opt
"developer machine" but it is recommended that you use a Dedicated MySQL Server Machine for your
MySQL database, if this is not an option then select "Server Machine".
If you selected Dedicated MySQL Server Machine and your MySQL service does not start after the wizard
completes, then try to re-run the wizard (or re-install) MySQL, but this time select the Server Machine
option.

I have checked "Multifunctional databases" as I wanted MyISAM as default storage engine but if you want
you can select "Transactional Database Only", this will make sure that InnoDB is the main storage engine. If
you have checked 3rd option then only myISAM engine would be available

Select the drive where the database files will be stored.


Select the drive on the fastest drive(s) on your server

It is recommended that you leave the default port 3306 in place, however
EventSentry will also work with non-standard ports if necessary.

It is highly recommended that you run the MySQL Server as a Windows


service(you can disable this if you want to start it manually whenever required) and include the binary
directory in the search path.

Specify a secure root password, you may want to check the box Enable root access
from remote machines if you plan on administering your MySQL server
from your workstation or other servers.
If you are getting an error message after clicking the Next button, then please enable port 3306
in the Windows XP Firewall Settings

Done!!!
But if you are installing MySQL on a Windows XP workstation, or any other computer that has a firewall
enabled, and the wizard fails with an error message similar to the one shown below (Can't connect to MySQL
server on 'localhost'), then you will have to exclude the MySQL daemon from your firewall configuration

On Windows XP, you can exclude MySQL from the firewall by following the steps below:
1. Navigate to Start -> Settings -> Control Panel -> Windows Firewall

2. In the resulting dialog, enter the information as shown in the screenshot

After clicking OK twice, return to the MySQL error message and select Retry. MySQL should now be able to create the
instance correctly

PRACTICAL-2

Install and use of SQLyog.

SQLyog is a GUI tool for the RDBMS MySQL. It is developed by Webyog.


SQLyog provides you with powerful means to manage your MySQL databases.

Runs on all Windows version from Win XP to Win 8.x (desktop systems) as well
as "Windows Server" systems of same generations (Windows Server 2003 and
higher).

MySQL 5.x compatible

Create/Drop/Alter Tables, Stored Procedures, Functions, Views, Triggers and


Events.

HTTP and SSH Tunneling - smartly manage your MySQL server even if the
MySQL port is blocked or remote access to MySQL is disallowed!

Protect your data with SSL encryption.

Smart AutoComplete.

Formats SQL statements.

Proactive Query Profiler.

Favorite Manager to neatly organize your favorite SQL statements.

Very fast retrieval of data.

Advanced GUI Query Builder. Supports JOINs, aggregate as well as 'common'


functions, sorting (ORDER BY) and filtering (WHERE and HAVING) and ALIAS.

SQLyog Import External Data wizard - use the GUI or specify a query.

Schema and Data synchronization tools.

Powerful compressed Scheduled Backup with email notification.

Schedule various jobs.

SQL Scheduler and Reporting Tool - execute unattended queries for database
maintainence of data verification with flexible email option.

Update result returned from query - also supports queries with JOINs. No
dialogues - just edit!

Manage foreign key relationships.

Fully InnoDB compliant.

Supports MySQL pluggable storage engines architecture.

Multi-threaded query execution with option to allow multiple query execution


simultaneously.

View your results in GRID/TEXT mode.

Filter data and resultsets directly form the context menu of a displayed value.

Execute (very large) SQL-scripts as batch files.

Execute multiple queries returning more than 1000s of rows per resultset. Its very
efficient in memory.

Very compact binary.

Written entirely in C/C++/Win32 APIs using native MySQL C APIs. No wrapper


classes used.

Connection manager.

Tabbed interface to create/alter tables.

View and edit advanced table-properties, such as Comment, Key_Length etc.

Do table-diagnostics (check, optimize, repair, analyze)

Duplicate tables to new table-names.

Excel like grid interface to edit data with support for Enum/Set.

Create/Drop databases.

Manage indexes.

Comprehensive user/security manager. Control every available privilege on what


level you like (server/database/table/column).

Reorder columns of table.

Copy database between two MySQL hosts.

Drop all tables of a database with a single click.

Edit BLOBs in TEXT or GRAPICHS mode. All common (non-proprioritary)


graphics format (including 'high-resolution' TIFFs and PNGs) supported.

Export table-structure and data into SQL-dumps.

Direct export to Microsoft Excel.

Export/import data in/from CSV files.

Export database schema in HTML.

Log all queries for a session.

Syntax-highlighting.

Save resultset in CSV, HTML and XML.

Copy your result as CSV to clipboard.

Is very keyboard friendly. You can work with 99% features of SQLyog with
keyboard.

View and kill other user-processes.

Flush Host/Logs/Privileges/Tables.

Quick access to processlist, status, variables etc.

once you are at the download page for the Community Edition, select the latest version.
You can select either the latest beta version or the latest stable release. After you have
downloaded it, run the file to install SQLyog. The installation part is pretty
straightforward, Once you have SQLyog installed, go ahead and start it. Follow along
with these next screenshots to get it set up with your local MySQL Server connection.

Think of localhost as an alias for the IP address (or in this case MySQL Host Address)
of the computer you are on.

PRACTICAL-3

Install and use of phpmyadmin.

phpMyAdmin is a free and open source tool written in PHP intended to


handle the administration of MySQL with the use of a web browser. It can
perform various tasks such as creating, modifying or
deleting databases, tables, fields or rows; executing SQL statements; or
managing users and permissions.

Features
1. Web interface

2. MySQL database management


3. Import data from CSV and SQL
4. Export data to various formats: CSV, SQL, XML, PDF (via
the TCPDF library), ISO/IEC 26300 - OpenDocument Text and
Spreadsheet, Word, Excel, LaTeX and others
5. Administering multiple servers
6. Creating PDF graphics of the database layout
7. Creating complex queries using Query-by-Example (QBE)
8. Searching globally in a database or a subset of it
9. Transforming stored data into any format using a set of predefined
functions, like displaying BLOB-data as image or download-link
10.
Live charts to monitor MySQL server activity like connections,
processes, CPU/Memory usage, etc.

http://your serverip/phpmyadmin/ now you should see the following screen


here you need to enter your mysql database details username as root
password as your mysql server root password by default mysql root users
doesn't have any password after entering these details press enter now.

Once you enter in to the phpmyadmin you should see the following screen

Creating Database
Now you need to create a database for this you can see the create database
option in the above screen there you need to enter the database name and
click on create

Creating a table in your database


The left-hand frame in phpMyAdmin is used for navigation, when you log in,
you'll see the database you created displaying in this area. Tables will also
show up under each database once they are created.
Click on the database you created in the navigation frame and
a new window will appear on the right hand side.

We will now create the first table in the database, called "details". This is
done by using the Create new table feature. The name of the new table is
typed into the Name: field, and the number of columns in the table (4) into
Fields:. Please note that when you create your own databases and tables,
it's wise to plan them out carefully to allow for growth - this exercise is only
meant to help you to familiarize with basic php/MySQL/phpMyAdmin
functions.
After you click Go a screen similar to the following should appear. Notice that
the table title will now also appear under the database name in the left hand
navigation frame.

We now need to enter the names and attributes of our table fields. Enter the
following information:
Field
Type
id
int
name
char
telephone char
date
char

Length
6
100
50
50

The Length value indicates the maximum allowable length of characters for
input. There are many different values that can be set for Type; view further
documentation here. The Types specified in this example aren't the most
efficient, but just used for the purposes of this exercise. The "id" field, which
will be used as a Primary key for this table, has been set to auto_increment,
saving you from having to having to type in the next number in sequence
when you input records.
Once you've entered all the values, click Save. A screen similar to the
following will appear.

Now the table is now created. You'll notice that the corresponding SQL
command for creating these fields is also displayed. While you don't really
need to know this for the purposes of this exercise, it doesn't hurt to get
familiar with the lingo over time.
Also on this page, you'll see many other options - explore these later on
once you are familiar with the way everything is working.
Inserting data into the table
Inputting data into your new table is easy. On the current screen, there's a
tab labeled "Insert" - click this and another window should appear, similar to
the following.

Simply type in details for each of the fields for this record. As the "id"
column was specified to automatically increment, you will not need to enter
a number. This number will be unique, no other record will have it and it will
be added once the record is saved.
If you ever get lost while getting familiar with phpMyAdmin navigation,
simply click "Home" in the left hand nav bar and start again.
After you click Save, the record is saved to the details table, and the
previous window we saw reappears with the SQL command for the insert.
Additional records can be added by re-selecting Insert". If you are going to
be inserting multiple records, you can also select the "Insert another new
row" radio button on the input form.

Once you've entered a number of records into the table, you can review the
records by clicking on the Browse tab. You can also select individual records
for editing or deleting.

Once your database starts growing and you don't wish to flick through pages
and pages of records, you can utilize the Select tab to refine displays.
Backing up your database
Click on your database name in the left hand navigation bar
- Click on EXPORT (top tab)
- Highlight the table/s you want to back up
You can select the whichever option is useful for your under export .If you
want save as file enter the file name and if you want use compression select
the available option for this.

you've created a database, a table and fields, entered in a few records,


viewed the records, edited and perhaps deleted some of them and practiced
backing up.I hope this will help some users how to use phpmyadmin.

PRACTICAL-4
Browser.

Install and use of MYSQL

The MySQL Query Browser is a graphical tool designed to provide a user friendly
environment in which to construct and execute SQL statements.
MySQL Query Browser is a cross-platform GUI client program thats intuitive and easy to
use. It provides a graphical interface to the MySQL server for querying and analyzing data.
Its similar in style of use to MySQL Administrator but is oriented toward accessing database
contents rather than server administration.
The following list describes some of the ways that you can use MySQL Query Browser:

Interactively enter, edit, and execute queries.

Navigate result sets with scrolling. Multiple result sets are tabbed so that you can
switch between them easily by selecting the appropriate tab.

Browse the databases available on the server, the tables and stored routines in
databases, and the columns in tables.

Browse your query history to see what queries youve issued, or recall and reexecute previous queries.

Bookmark queries for easy recall.

Create or drop databases and tables, and modify the structure of existing tables.

Create and edit SQL scripts, with debugging.

Edit connection profiles that can be used to connect to servers more easily.

Access information from the MySQL Reference Manual, such as statement syntax and
function descriptions.

MySQL Query Browser supports multiple server connections and opens a separate window
for each connection that you establish.

Connecting the MySQL Query Browser to a Database Server

When the MySQL Query Browser tool starts the following login screen will appear:

Enter the name of the host on which the database server resides, together with appropriate
user and password credentials. Finally, specify the name of database in the Default
Schema field on which you wish to work during the Query Browser session (note that you
can switch to a different database later from within the tool). Click on the Connect button to
connect to the specified server.
Once connected to a database server, the following screen should appear:

At the top of the window is a large text input field. This is where SQL statements are typed
by the user. Statements can be entered on multiple lines and are not executed until the
execute button is pressed (the round green button with the white lightning bolt). An
executing statement can be stopped by pressing the red stop button.
The Back and Next buttons provide a way to page through the history of executed
commands.
The large gray area in the center of the screen displays the results of the executed
statements. An additional section at the bottom of the window appears to display any errors
encountered as a result of a SQL statement. Additional Resultset pages may be added from
the File->New Query Tab menu option.
In the top right hand side of the window is a list of databases available on the server to
which the tool is currently connected. Clicking the arrow next to any database will display
the tables contained therein. Clicking on the arrow next to a table will similarly list the
columns in that table. Right clicking with the mouse in this area pops up a menu providing
options to create new tables, views and databases. This menu also provides an option to
select a different schema to the one chosen at the login screen and provides the option to
drop the currently highlight table or database.
The bottom right side of the main window provides a list of help topics. Double clicking on a
list item will display help text in the result area of the screen. To return to the results page,
either close theSQL Help tab, or click on the Resultset tab.

Executing SQL Statements


To execute a SQL statement in the MySQL Query Browser, simply type the command into
the text field at the top of the main screen. The text input field is free format, allowing you
to press enter in order to spread a statement over multiple lines. As with all SQL
statements, the completed statement must be terminated with a semi-colon (;). Pressing
the execute button will cause the statement to be executed and the output to be displayed
in the results area. The following figure shows the result of running a SHOW
DATABASES; command:

PRACTICAL-5
Install and use of MYSQL
Administrator.
MySQL Administrator is a program for performing administrative operations, such
as configuring, monitoring and starting and stopping a MySQL server, managing
users and connections, performing backups, and a number of other administrative
tasks.
Most tasks can be performed using a command-line client such as mysqladmin, or
mysql, but MySQL Administrator has the following advantages:

Its graphical user interface makes it more intuitive.


It provides a better overview of the settings that are crucial for the performance,
reliability, and security of your MySQL servers.
It displays performance indicators graphically, thus making it easier to determine
and tune server settings

Once MySQL Administrator has been started, it displays a connection dialog box.
Specify the MySQL server you would like to connect to, the necessary credentials,
and both the host and port. You may also specify a number of additional options, if
required.
For example, to connect to a newly installed server running on the same machine
ad the administrative (root) user you would the
host localhost, the user root and the password that you sent during installation (or
blank if you haven't set one).

How to use MySQL Administrator to backup a database


STEP 1.Enter the login details for the MySQL connection. The Server Host should be your domain
name and you can use your cPanel login details in order to access all databases in your account.
Alternatively, you can use the MySQL username you have created through the MySQL Databases
tool in your cPanel in order to connect to the database that it has access to. You should leave the
Port setting to its default value - 3306.
Once you have entered your credentials, click on the OK button.

STEP 2.Once you have logged in, a screen with the MySQL server status will appear. If you are
using the application on a local server you will be able to execute administrative tasks like restarting
the MySQL server for example. On a Shared hosting account, however, you can only create
backups and restore your databases with this application.

STEP 3.To create a backup of your database, click on the "Backup" button from the left menu. Then
click on the "New Project" button, set the name for your backup and click on the "Save Project"
button.

STEP 4.Once you have created a project, you have to select which databases you want to backup.
To do this, mark the database from the left column that shows the available databases. Next, click on
the right-pointing arrow to mark the database for backup. Once you have done that, click on the
"Execute Backup Now" button in order to start the backup of your database.

STEP 5.The application will ask you where to store the backup file of your database. Select a
suitable location on your local computer and click on the "Save" button.

How to use MySQL Administrator to restore a database


STEP 1.Click on the "Restore" Button from the left menu. Next, press the "Open Backup File" button
at the bottom of your screen. Locate and open the .sql file you have previously created using the
Backup option.

STEP 2.The MySQL Administrator application will automatically detect which database should be
restored. All you have to do is press the "Start Restore" button to initiate the backup restore.

How to use MySQL Query Browser to access a database and


execute queries on it
STEP 1.The MySQL Query Browser application has a similar interface to the MySQL Administrator
application. First you have to enter the login details for the MySQL connection. The Server Host
should be your domain name and you can use your cPanel login details in order to access all of the
databases on your account. Alternatively, you can use the MySQL username you have created
through the MySQL Databases tool in your cPanel. You should leave the Port setting to its default
value - 3306. Once you have entered your login details, press the OK button.

STEP 2.On the right part of the screen you will notice a list of the databases on your account.
Double-click on the one that you would like to work with. Then just type your queries and press the
"Execute Query" button displayed with a little
icon.

Well done! You are now fully able to execute queries on your database as if you are working on your
local MySQL server!

PRACTICAL-6
Create table and perform various task such
as Create a product and
product_price_history table. The price of
product change constantly. Write a trigger
for updating product_price_history table
when product price change in product table
and such other database can be explored.

What is Trigger
A SQL trigger is a set of SQL statements stored in the database catalog. A SQL
trigger is executed or fired whenever an event associated with a table occurs
e.g., insert, update or delete.
A SQL trigger is a special type of stored procedure. It is special because it is not
called directly like a stored procedure. The main difference between a trigger
and a stored procedure is that a trigger is called automatically when a data
modification event is made against a table whereas a stored procedure must be
called explicitly.
It is important to understand SQL triggers advantages and disadvantages so
that you can use it appropriately. In the following sections, we will discuss about
the advantages and disadvantages of using SQL triggers.
Advantages of using SQL triggers

SQL triggers provide an alternative way to check the integrity of data.

SQL triggers can catch errors in business logic in the database layer.

SQL triggers provide an alternative way to run scheduled tasks. By using SQL
triggers, you dont have to wait to run the scheduled tasks because the triggers are
invoked automatically before or after a change is made to the data in tables.

SQL triggers are very useful to audit the changes of data in tables.

Disadvantages of using SQL triggers

SQL triggers only can provide an extended validation and they cannot replace all the
validations. Some simple validations have to be done in the application layer. For
example, you can validate users inputs in the client side by using JavaScript or in the
server side using server side scripting languages such as JSP, PHP, ASP.NET, Perl,
etc.

SQL triggers are invoked and executed invisibly from client-applications therefore it is
difficult to figure out what happen in the database layer.

SQL triggers may increase the overhead of the database server.

Syntax:
DELIMITER $$

CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
TRIGGER `DATABASE NAME`.`TRIGGER NAME` BEFORE/AFTER
INSERT/UPDATE/DELETE
ON `DATABASE NAME`.`TABLE NAME `
FOR EACH ROW BEGIN

END$$

DELIMITER ;

MySQL trigger example

DELIMITER $$

CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
TRIGGER `amit`.`updatedata1` AFTER UPDATE
ON `amit`.`product_master`
FOR EACH ROW BEGIN
update product_history set P_Price=NEW.P_Price where P_ID=NEW.P_ID;

END$$

DELIMITER ;

PRACTICAL-7
Implement and Manipulate
Trigger Such as Create a trigger for deleting
all the products of particular product type
when that product type is deleted and similar
for other database.

DELIMITER $$

CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
TRIGGER `amit`.`updatedata1` AFTER Delete
ON `amit`.`product_type`
FOR EACH ROW BEGIN

Delete from product_master WHERE P_TYPE=OLD.P_TYPE;


END$$

DELIMITER ;

PRACTICAL-8
Write stored routines such as write a routine
for counting all product types and other such
routines can be performed.

What is mysql stored procedure:


Stored procedure is set of SQL code which is stored in database server and
can be invoked by program or trigger or stored procedure itself. Stored
procedure is way to execute may task on your database server directly, in
other words stored procedure is way to execute your business logic directly
into database server.
In stored procedure you can perform your some of generic tasks which are
dependent to database table data. so rather to go multiple time on database
to fetch data into your program and perform your business logic stored
procedure give some generic way of coding for your business logic and take
data return or you can save your processed data into your database.
Let us take an example: Suppose you have normal banking system where

you want to update interest of loan of any specific user. What you will normally
do from your program? You will fetch capital, rate of interest and duration and
calculate interest and then you will go back to database and save data. In this
very small example we are going 2 time in database, but if we will use the
stored procedure then we need to write all operation within our stored
procedure and we will call it through the program one time. In this case you
will fetch data like capital, rate of interest and duration within database(with
stored procedure) and you will save data after processing. In this case we are
only interrupting database server one time. Thanks to the stored procedure
which reduced our server overhead.

Advantage of Mysql Stored Procedure:


Following are the condition when mysql stored procedure are very useful:

Multiple applications are running in multiple environment and need to


use the same database. By using stored procedure you can make your
business logic independent of programming language.

When security is main concern use of stored procedure is vital. By doing


your operation through the database you can log your all performed
action. Banking site is the best example.

If you are using stored procedure then you do not have table access
directly which is one more way to secure the data and transaction.

Stored procedure increases performance of your application sometime.


When stored procedure created it complie and when it call it never go to
parser and direclty execute and fetch the record whereas normal SQL

query fired on database server get parse every time so using stored
procedure your can save parsing time.

If your application is big or your database server on remote system then


by using stored procedure you can decrease the traffic between your
database server and application server.

Since stored procedure is written in your database server and


application call it sepratly then the degree of re-usability increase
because despite to going in much detail you can call stored procedure to
perform your action.

Disadvantages of using stored procedure :


Following are situation due to which we should avoid using mysql store
procedure.

Sometime use of stored procedure is bit risky. Store procedure follow


define one use many time philosophy. Doing change in stored
procedure directly effect your data so it should always be use with very
carefully.

Stored procedure are set of sql command form our logic so sometime
programmer need to debug the stored procedure. In mysql stored
procedure it is very hard to debug.

Managing stored procedure is bit difficult because it does not have any
object oriented paradigm like things.

Mysql stored procedure never return value directly. Either you need to
specify output parameter in your stored procedure or you have to put select

statement inside the procedure which will fill data in your resource.
Creation of the mysql procedure involve 3 steps

Definition of the procedure: Create procedure syntex with the name

Definition of the input parameter: There are three type of parameter you
can define. in parameter, out parameter and inout parameter.
By in parameter you can define inputs of the stored procedure,
By out parameter you can specify the output parameter. By inout you can
define shared parameter, it can be used either as input parameter or
output parameter.

Third is the body of the procedure. Normally we write within the BEGIN
and END tag.

Syantax:
DELIMITER $$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
PROCEDURE `amit`.`countSP`()
/*LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }

| COMMENT 'string'*/
BEGIN
END$$
DELIMITER ;

EXAMPLE
DELIMITER $$

CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
PROCEDURE `amit`.`SpCount`(In ID Int)
BEGIN
Select Count(*) as total from product_master where P_ID=ID;
END$$
DELIMITER ;

EXAMPLE
DELIMITER $$

CREATE
/*[DEFINER = { user | CURRENT_USER }]*/
PROCEDURE `amit`.`AllCountSP`()

BEGIN
Select Count(*) as total From product_type;
END$$
DELIMITER ;

PRACTICAL-9
Manipulate on routines such as write a routine for
updating price of all products by 5% and other
such routines can be performed
DELIMITER $$

CREATE

/*[DEFINER = { user | CURRENT_USER }]*/


PROCEDURE `amit`.`UPCHANGESP`(In price int)
BEGIN
update product_master set P_Price=P_Price+
(P_Price*price);
END$$

DELIMITER ;

PRACTICAL-10
Create cursors such as create a cursor for selecting
all product whose price is more than 1000 and
other such cursors can be implemented

In computer science and technology, a database cursor is a control structure


that enables traversal over the records in a database. Cursors facilitate
subsequent processing in conjunction with the traversal, such as retrieval,

addition and removal of database records. The database cursor characteristic


of traversal makes cursors akin to the programming language concept of
iterator.
Cursor is only available from MySQL version 5 or greater. By using cursor you
can get specific records from your database and traverse in every row of the
database. For example, if you want to take every employee basic salary from
the salary table and add calculate gross salary for this month. Then you can
use cursor to get all active employee basic salary from table. And then by the
help of MySQL cursor you can go to every employee salary and calculate his
gross salary. So in nutshell cursor is a kind of loop facility provided in mysql
to traverse to every row and manipulate data. I am using
word manipulation because if you do not require any big manipulation then
you can fetch record from join as well. So decide carefull if you should choose
MySQL cursor implementation in your procedure or not. There are
some advantages and disadvantages of
using MySQL cursor. MySQL Cursor his having following 3 properties:
1. Asensitive: Means cursor can not create copy of table.
In MySQL cursor just traverse on every row of the table or result set.
2. Read Only: By help of mysql cursor you can not update any table. But
in the loop and row traversal you can take data from cursor and
do update But directly from mysql cursor you can not write cursor like
declare curs1 cursor for Update test111 set id=2.
3. One directional: Mysql Cursor always move in one direction. I mean
top to bottom in result set. If you want to traverse in backward direction
directly then it is not possible.

Advantage of using MySQL Cursor

Following are some of the advantage of using MySQL cursor:


1. No need to write business logic after fetching data from your code logic.
2. Gives you better flexibility for operating even on the single column of the
row. Manipulation become always easy.
3. Saves you from the simplex join structure.
4. Easy to maintain the business logic of your application at one place.

Disadvantage of using Mysql Cursor


Following are some of the disadvantages of using cursor in MySQL:
1. Slow down your stored procedure or function performance in cause of
large record set in cursor.
2. Debugging of your business logic become tough.
3. Hard to manage.
4. Need extra care in cause of the implementation of replication using
binary log.
5. Need to consider locking of the database.
After thinking and evaluating its advantages and disadvantages you can
decide to choose cursor implementation in your procedure. If you have
decided to use cursor in your procedure blow stuffs are for you.

How to create Cursor in Mysql

As mysql cursor can only be implemented in stored procedure and function.


First you need to create any stored procedure or function. We will take
example of the stored procedure here. First of all you need to declare a mysql
cursor. Also you need to declare the variable where you will store value of the
cursor for the data manipulation. And then you need to create handler for the
cursor. Handler in MySQL are specific event controls. For example if you have
created handler for not found then in case of not found handler get fired.
Following is the complete example of your mysql cursor:
DELIMITER $$
USE `test`$$
DROP PROCEDURE IF EXISTS `test`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `test`()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE i INTEGER;
DECLARE n TEXT;
DECLARE curs1 CURSOR FOR SELECT `id`, `name` FROM
test111;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN curs1;
read_loop: LOOP
FETCH curs1 INTO i,n;
IF done THEN
LEAVE read_loop;
END IF;
SELECT i,n;
END LOOP;
CLOSE curs1;

END$$
DELIMITER ;
Above mysql cursor is same as my basic structure which I have shown
in beginning of my example. Only thing I have added is Handler and loop.
Without handler and loop you can not implement cursor. Let us examine all
process. First at the declaration block I have declare following variable
DECLARE done INT DEFAULT FALSE;
DECLARE i INTEGER;
DECLARE n TEXT;
DECLARE curs1 CURSOR FOR SELECT `id`, `name` FROM
test111;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
Variable done is used in handler. By default its value is false. Once data not
found event will trigger in cursor it will be true.
Second variable is i and n. Both will be used in cursor. They will get data
assigned by cursor.
Next is variable curs1. This is your mysql cursor variable. DECLARE curs1
CURSOR FOR SELECT `id`, `name` FROM test111. In this declation I am
telling mysql to create cursor for the query select id and name from test111
table.
Last and most important is handler. DECLARE CONTINUE HANDLER FOR
NOT FOUND SET done = TRUE. In this declation I am telling mysql to fire
activity(set done = true) once any not found event occur. So once not found
event occur anywhere in your cursor variable done will be true.
Now our body part is:

OPEN curs1;
read_loop: LOOP
FETCH curs1 INTO i,n;
IF done THEN
LEAVE read_loop;
END IF;
SELECT i,n;
END LOOP;
CLOSE curs1;
So by using OPEN curs1 I am saying MySQL to open my cursor. You always
need to open and close the cursor.We will close the cursor in later part.
Next we have declared loop with name read_loop. It will start iterating the
cursor. After starting the loop we have given command to fetch data from
cursor and put it in i and n variable respectively. Now cursor will be iterated
and goes to every record of your table. And will assign value from table in
variable i and n. Cursor will reach to last or if data will not found your handler
will make variable done true. So we have applied if condition and checking if
our variable done is true or false. Once your variable will be trur(data not
found). We are exiting the loop.
IF done THEN
LEAVE read_loop;
END IF;
So if you will not write above condition your cursor will always iterated.And
you will go to infinite loop. So be careful. My above example will
return serious result set. If you have 100 record in your table test111 then you

will get 100 result set. Now this is very bad implementation but yet simple for
the MySQL cursor.
Example
DELIMITER $$
DROP PROCEDURE IF EXISTS `amit`.`test2`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `test2`()
BEGIN
DECLARE done INT DEFAULT FALSE;
Declare total_row int;
Declare curs1 Cursor for Select count(*) From product_master where
P_Price>=1000;
OPEN curs1;
read_loop:LOOP
FETCH curs1 into total_row;
IF done THEN
LEAVE read_loop;
END IF;
SELECT total_row;
END LOOP;
CLOSE curs1;
END$$
DELIMITER ;

PRACTICAL-11
Perform various event handling operations

Events
An Event is a scheduled job executed by the MySQL server itself. Events are
supporoted from MySQL 5.1. If your MySQL version does not support events you
should note that SQLyog has the 'Notifications Service' facility which in most situations
will make it possible for you to achieve the same.
The differences between Events and Notifications Service can be summarized as
follows:

Events require specific server versions - Notifications Service works with every MySQL
version.

Events are executed by the server without the need of any external client to connect (but
the server does actually start a client instance internally) - Notifications Service creates an
ordinary client connection.

Events may only execute SQL statements. It cannot perform file system operations,
invoke external binaries etc. - Notifications Service can only execute SQL. As it is managed
by the Operating System and not the MySQL server, it can be executed by a batch job or an
application which copies files.

Events have no notifications feature - Notifications Service has (that is why it is named
as it is!).

You can see that each has advantages and drawbacks. They may also be combined.
For instance you can have an Event scheduled at close interval (say 1 minute) that
updates a table used by a Notifications Service Job executed at larger intervals (like
once per hours).

Create Event

To create a new event, use the menu item Others -> Event-> Create Event or use the
database context menu.
Enter the event name in the appeared dialog, and SQLyog will present a template for
your Event in a separate tab of the SQL Window. The template contains a 'skeleton' for
defining three common types of Event:

Events that runs only once

Events that run forever after creating

Events defined to start and/or stop at a specified time.

Uncomment the one that is closest to what you want and also uncomment any nondefault options you want to use for the Event.
To create a useful Event there must of course be some code in between the BEGIN ..
END sequence. That can be any valid SQL. If there are more SQL statements here they
must be separated by ";" (semicolon). To conclude the Event code you must use a userdefined DELIMITER as the default SQL delimiter (;) is used between BEGIN... END
internally in the Event code . More details about this in the paragraph on delimiters.

Alter Event

To alter an existing event, right-click it in the Object browser or use the menu
itemOthers -> Event -> Alter Event or press F6.
The current Event definiton will appear in a separate tab of the SQL Window. Change
what you want and next use the toolbar buttons or hotkeys to execute the queries. As
editor tabs of a special kind are used for 'stored programs' creation/alteration, pressing
both F5 and Shift+F5 keys leads to execution of all queries present in the SQL window.
If you want to use the template for Create Event you may also open the Create Event
template and simply replace the word CREATE with ALTER.
The first option is easiest if you only want to change a few details of the Event code. If
you want to completely redesign the schedule you may prefer the second option.

Drop Event

To drop an existing event, right click it in the Object browser and use the menu
itemOthers -> Event -> Drop Event. Then confirm the operation in the appeared
dialog.

Rename Event

To rename an event, right-click it in the Object browser and use the menu item Others
-> Event -> Rename Event or simply click its name in the Object browser or press F2.
'Rename Event' is special variation of 'Alter Event'.

Example:
DELIMITER $$
SET GLOBAL event_scheduler = ON$$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/ EVENT
`amit`.`MyEvent19`
ON SCHEDULE EVERY 2 SECOND
-- scheduleexample 3: specified start time, end time and interval for
execution
/*EVERY 1 [HOUR|MONTH|WEEK|DAY|MINUTE|...]
-- STARTS CURRENT_TIMESTAMP/'YYYY-MM-DD HH:MM.SS' { + INTERVAL
1[HOUR|MONTH|WEEK|DAY|MINUTE|...] }
-- ENDS CURRENT_TIMESTAMP/'YYYY-MM-DD HH:MM.SS' { + INTERVAL 1
[HOUR|MONTH|WEEK|DAY|MINUTE|...] } */
ON COMPLETION PRESERVE
ENABLE
DO
BEGIN
DECLARE v int;
SELECT count(*) as total INTO v from `Product_master` where
`P_Qyantity`<25;
SELECT v;
END$$
DELIMITER ;

PRACTICAL-12
Implement events such as create an event that update the product Quantity.
DELIMITER $$
SET GLOBAL event_scheduler = ON$$
CREATE
/*[DEFINER = { user | CURRENT_USER }]*/ EVENT
`amit`.`MyEvent19`
ON SCHEDULE EVERY 2 SECOND
-- scheduleexample 3: specified start time, end time and interval for
execution
/*EVERY 1 [HOUR|MONTH|WEEK|DAY|MINUTE|...]
-- STARTS CURRENT_TIMESTAMP/'YYYY-MM-DD HH:MM.SS' { + INTERVAL
1[HOUR|MONTH|WEEK|DAY|MINUTE|...] }
-- ENDS CURRENT_TIMESTAMP/'YYYY-MM-DD HH:MM.SS' { + INTERVAL 1
[HOUR|MONTH|WEEK|DAY|MINUTE|...] } */
ON COMPLETION PRESERVE
ENABLE
DO
BEGIN
update product_master set `P_Quantity`=20 where `P_Quantity`<25;
END$$
DELIMITER ;

PRACTICAL-13

Create and manage user accounts in MySQL


Lets start by making a new user within the MySQL shell:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

at this point newuser has no permissions to do anything with the databases. In fact, if
newuser even tries to login (with the password, password), they will not be able to reach
the MySQL shell.
Example:
create user 'AGP@localhost' identified by 'password';
To get a list of MySQL users:
If you are running a multi-user MySQL database, handy commands that show a list of all
existing MySQL users

select user from mysql.user;

The above output shows a list of existing MySQL accounts. Note that a MySQL account has
two components: user and host. This allows the same user to use different MySQL
accounts depending on which host they are connecting from. "%" is a wildcard character
interpreted as "any" host.

select user ,host from mysql.user;

PRACTICAL-14

Practice with GRANT and Revoke Command


To find the privilege(s) granted to a particular MySQL account:

show grants for 'sspc'@'%';

Therefore, the first thing to do is to provide the user with access to the information they
will need. The asterisks in this command refer to the database and table (respectively)
that they can accessthis specific command allows to the user to read, edit, execute
and perform all tasks across all the databases and tables.

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

Example:
show grants for 'newuser'@'localhost';

Once you have finalized the permissions that you want to set up for your new users,
always be sure to reload all the privileges.
1. Flush PRIVILEGES
FLUSH PRIVILEGES command can be used before and after adding new users.This
command simply reloads the grant tables in your MySQL database by enabling the changes
to take effect without stopping and restarting MySQL

Example
FLUSH PRIVILEGES;

How To Grant Different User Permissions


Here is a short list of other common possible permissions that users can enjoy.

ALL PRIVILEGES- as we saw previously, this would allow a MySQL user all
access to a designated database (or if no database is selected, across the
system)

CREATE- allows them to create new tables or databases

DROP- allows them to them to delete tables or databases

DELETE- allows them to delete rows from tables

INSERT- allows them to insert rows into tables

SELECT- allows them to use the Select command to read through databases

UPDATE- allow them to update table rows

GRANT OPTION- allows them to grant or remove other users' privileges

To provide a specific user with a permission, you can use this framework:
GRANT [type of permission] ON [database name].[table name] TO
[username]@'localhost;

If you want to give them access to any database or to any table, make sure to put an
asterisk (*) in the place of the database name or table name.
Each time you update or change a permission be sure to use the Flush Privileges
command.

REVOKE Command
If you need to revoke permission, the structure is almost identical to granting it:
REVOKE [type of permission] ON [database name].[table name] FROM
[username]@localhost;

Example:
REVOKE DELETE on amit.test1 FROM 'root'@'localhost';
Just as you can delete databases with DROP, you can use DROP to delete a user
altogether:
DROP USER demo@localhost;

Example:
DROP USER 'root'@'localhost' ;
To test out your new user, log out by typing
Quit

PRACTICAL-15

Practice with database backup and recovery


operations as well security operations
It is important to back up your databases so that you can recover your data and be up and running
again in case problems occur, such as system crashes, hardware failures, or users deleting data by
mistake. Backups are also essential as a safeguard before upgrading a MySQL installation, and they
can be used to transfer a MySQL installation to another system or to set up replication slave servers.
MySQL offers a variety of backup strategies from which you can choose the methods that best suit
the requirements for your installation.

Back up From the Command Line (using mysqldump)


If you have shell or telnet access to your web server, you can backup your MySQL data by
using the mysqldump command. This command connects to the MySQL server and creates
an SQL dump file. The dump file contains the SQL statements necessary to re-create the
database. Here is the proper syntax:
$ mysqldump --opt -u [uname] -p[pass] [dbname] > [backupfile.sql]

Your database username


The password for your database (note there is no space between -p and the
password)
[dbname] The name of your database
[backupfile.sql] The filename for your database backup
[--opt] The mysqldump option
[uname]
[pass]

For example, to backup a database named 'Tutorials' with the username 'root' and with no
password to a file tut_backup.sql, you should accomplish this command:
$ mysqldump -u root -p Tutorials > tut_backup.sql

This command will backup the 'Tutorials' database into a file called tut_backup.sql which will
contain all the SQL statements needed to re-create the database.
With mysqldump command you can specify certain tables of your database you want to
backup. For example, to back up only php_tutorials and asp_tutorials tables from the
'Tutorials' database accomplish the command below. Each table name has to be separated
by space.
$ mysqldump -u root -p Tutorials php_tutorials asp_tutorials > tut_backup.sql

Sometimes it is necessary to back up more that one database at once. In this case you can
use the --database option followed by the list of databases you would like to backup. Each
database name has to be separated by space.
$ mysqldump -u root -p --databases Tutorials Articles Comments > content_backup.sql

If you want to back up all the databases in the server at one time you should use the --alldatabases option. It tells MySQL to dump all the databases it has in storage.
$ mysqldump -u root -p --all-databases > alldb_backup.sql

The mysqldump command has also some other useful options:


--add-drop-table:

the dump.
--no-data:

Tells MySQL to add a DROP TABLE statement before each CREATE TABLE in

Dumps only the database structure, not the contents.

--add-locks:

Adds the LOCK TABLES and UNLOCK TABLES statements you can see in the

dump file.
The mysqldump command has advantages and disadvantages. The advantages of using
mysqldump are that it is simple to use and it takes care of table locking issues for you. The
disadvantage is that the command locks tables. If the size of your tables is very
big mysqldump can lock out users for a long period of time.

Back up your MySQL Database with Compress


If your mysql database is very big, you might want to compress the output of mysqldump.
Just use the mysql backup command below and pipe the output to gzip, then you will get
the output as gzip file.
$ mysqldump -u [uname] -p[pass] [dbname] | gzip -9 > [backupfile.sql.gz]

If you want to extract the .gz file, use the command below:
$ gunzip [backupfile.sql.gz]

Restoring your MySQL Database


Above we backup the Tutorials database into tut_backup.sql file. To re-create the Tutorials
database you should follow two steps:

Create an appropriately named database on the target machine


Load the file using the mysql command:

$ mysql -u [uname] -p[pass] [db_to_restore] < [backupfile.sql]

Have a look how you can restore your tut_backup.sql file to the Tutorials database.
$ mysql -u root -p Tutorials < tut_backup.sql

To restore compressed backup files you can do the following:


gunzip < [backupfile.sql.gz] | mysql -u [uname] -p[pass] [dbname]

If you need to restore a database that already exists, you'll need to use mysqlimport
command. The syntax for mysqlimport is as follows:
mysqlimport -u [uname] -p[pass] [dbname] [backupfile.sql]

Вам также может понравиться