Introduction To Mysql: Open Source Software - Unit-Iii
Introduction To Mysql: Open Source Software - Unit-Iii
IV IT
Introduction to MySQL
The MySQL database system is a networked database system that uses a client-server
architecture that centers around the server , mysqld. The server is the program that actually
manipulates databases.
MySQL Client programs communicate to the server by means of statements written
in Structured Query Language (SQL).
machine from which we want to access MySQL, but the server can be installed anywhere, as
long as clients can connect to it.
One of the clients is the mysql program that is included in MySQL distributions.
When used interactively, mysql prompts us for a statement, sends it to the MySQL server for
execution, and then displays the results. mysql also can be used non interactively; for
example, to read statements from a file or from other programs. This enables us to use mysql
from within scripts or in conjunction with other applications.
IV IT
The following example shows how to use the mysql program to connect to the server and
issue a GRANT statement that sets up a user account with privileges for accessing a database
named cookbook. The arguments to mysql include -h localhost to connect to the MySQL
server running on the local host, -p to tell mysql to prompt for a password, and -u root to
connect as the MySQL root user.
The hostname part of 'cbuser'@'localhost' indicates the host from which we'll be
connecting to the MySQL server to access the cookbook database. To set up an account that
will connect to a server running on the local host, we can use localhost, as the host name. If
we plan to make connections to the server from another host, substitute that host in the
GRANT statement.
For example, if we'll be connecting to the server as cbuser from a host named 127.0.0.1, the
GRANT statement should look like this:
mysql> GRANT ALL ON cookbook.* TO 'cbuser'@'127.0.0.1' IDENTIFIED BY
'mysqlpass';
IV IT
Once we've connected successfully, using CREATE DATABASE command, the database
can be created.
For example
% mysql -h localhost -p -u cbuser
Enter password: cbpass
mysql> CREATE DATABASE cookbook;
Query OK, 1 row affected (0.08 sec)
Now the cookbook database is created, so we can create tables in it. Issue the following
statements to select cookbook as the default database, create a simple table, and populate it
with a few records:
mysql> USE cookbook;
mysql> CREATE TABLE limbs (thing VARCHAR(20), legs INT, arms INT);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('human',2,2);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('insect',6,0);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('squid',0,10);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('octopus',0,8);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('fish',0,0);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('centipede',100,0);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('table',4,0);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('tripod',3,0);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('Peg Leg Pete',1,2);
mysql> INSERT INTO limbs (thing,legs,arms) VALUES('space alien',NULL,NULL);
We can verify that the table contains the inserted rows by issuing a SELECT statement:
IV IT
If mysql tries to start but exits immediately with an "access denied" message, we'll need to
specify connection parameters. The most commonly needed parameters are the host to
connect to (the host where the MySQL server runs), our MySQL username, and a password.
For example:
% mysql -h localhost -p -u cbuser
Enter password: cbpass
The syntax and default values for the connection parameter options are shown in the
following table. These options have both a single-dash short form and a double-dash long
form.
Parameter type Option syntax forms Default value
Hostname -h hostname--host=hostname localhost
Username -u username--user=username Your login name
Password -p--password None
To terminate a mysql session, issue a QUIT statement:
mysql> QUIT
We can also terminate the session by issuing an EXIT statement or (under Unix) by typing
Ctrl-D.
IV IT
IV IT
IV IT
Perl Script
To write MySQL scripts in Perl, we should have the DBI module installed, as well as
the MySQL-specific driver module, DBD::mysql. Here is a simple Perl script that connects to
the cookbook database and then disconnects:
#!/usr/bin/perl
# connect.pl - connect to the MySQL server
use strict;
use warnings;
use DBI;
my $dsn = "DBI:mysql:host=localhost;database=cookbook";
my $dbh = DBI->connect ($dsn, "cbuser", "cbpass")
or die "Cannot connect to server\n";
print "Connected\n";
$dbh->disconnect ();
print "Disconnected\n";
% connect.pl
Connected
Disconnected
Ruby
To write MySQL scripts in Ruby, we should have the DBI module installed, as well
as the MySQL-specific driver module. Both are included in the Ruby DBI distribution.
Here is a simple Ruby script that connects to the cookbook database and then disconnects:
#!/usr/bin/ruby
# connect.rb - connect to the MySQL server
require "dbi"
begin
7
IV IT
dsn = "DBI:Mysql:host=localhost;database=cookbook"
dbh = DBI.connect(dsn, "cbuser", "cbpass")
puts "Connected"
rescue
puts "Cannot connect to server"
exit(1)
end
dbh.disconnect
puts "Disconnected"
% connect.rb
Connected
Disconnected
PHP
To write PHP scripts that use MySQL, the PHP interpreter must have MySQL
supporting feature. If it doesnt, our scripts will be unable to connect to our MySQL server.
PHP actually has two extensions that enable the use of MySQL. The first, mysql, is the
original MySQL extension. It provides a set of functions that have names beginning with
mysql_. The second, mysqli, or MySQL improved, provides functions with names that
begin with mysqli_.
<?php
$connect = mysql_connect("localhost", "root", "");
if(!$connect){
die("Cannot connect to MySQL server". mysql_error());
}else{
echo "Sucessfully connected to MySQL server";
}
$db = mysql_select_db("cookbook", $connect);
if(!$db){
die("Cannot select a database". mysql_error());
}else{
echo "Database is sucessfully selected";
} ?>
Python
To write MySQL programs in Python, we need the MySQLdb module that provides
MySQL connectivity.
#!/usr/bin/python
# connect.py - connect to the MySQL server
import sys
import MySQLdb
try:
8
IV IT
IV IT
Statements that do not return a result set (that is, a set of rows). Statements in this
IV IT
Ruby
As with Perl DBI, Ruby DBI provides two approaches to SQL statement execution.
With either approach, if a statement-execution method fails with an error, it raises an
exception.
For statements such as INSERT or UPDATE that return no result set, invoke the do( )
database handle method. Its return value indicates the number of rows affected.
For SELECT statement, execute( ) method is provided for returning result set.
For example:
The following example executes a SELECT statement and uses the fetch method to
retrieve the rows in a while loop:
count = 0
sth = dbh.execute("SELECT id, name, cats FROM profile")
while row = sth.fetch do
printf "id: %s, name: %s, cats: %s\n", row[0], row[1], row[2]
1
IV IT
count += 1
end
sth.finish
puts "Number of rows returned: #{count}"
PHP
To get PHP to execute the SQL DML statement, we must use the mysql_query()
function. This function is used to send a query or command to a MySQL connection.
For example
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
mysql_query("UPDATE Persons SET Age = '36'
WHERE FirstName = 'Peter' AND LastName = 'Griffin'");
mysql_close($con);
?>
To get PHP to execute the DCL statement like SELECT, we must use the
mysql_query() function. This function is used to send a query or command to a MySQL
connection and will get resultset object. Using the resultset object we will retrieve the rows
from the table.
For example
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
while($row = mysql_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysql_close($con);
?>
IV IT
Python
The Python DB-API interface does not have distinct calls for SQL statements that
return a result set and those that do not. To process a statement in Python, use the database
connection object to get a cursor object. Then use the cursors execute( ) method to send the
statement to the server. If the statement fails with an error, execute( ) raises an exception.
Otherwise, if there is no result set, the statement is completed, and we can use the cursors
rowcount attribute to determine how many rows were changed.
For example
cursor = conn.cursor ()
cursor.execute ("UPDATE profile SET cats = cats+1 WHERE name = 'Fred'")
print "Number of rows updated: %d" % cursor.rowcount
If the statement does return a result set, fetch its rows, and then close the set. DB-API
provides a couple of methods for retrieving rows
For example
cursor = conn.cursor ()
cursor.execute ("SELECT id, name, cats FROM profile")
rows = cursor.fetchall ()
for row in rows:
print "id: %s, name: %s, cats: %s" % (row[0], row[1], row[2])
print "Number of rows returned: %d" % cursor.rowcount
cursor.close ()
Java
To issue a statement, the first step is to get a Statement object by calling the
createStatement( ) method of our Connection object. Next using this object, we can send
SQL statements to MySQL server. JDBC provides several methods for doing this.
executeUpdate( ) for statements that dont return a result set, executeQuery( ) for statements
that do, and execute( ) when we dont know. Each method raises an exception if the
statement fails with an error.
Example for DML Statement
Statement s = conn.createStatement ();
int count = s.executeUpdate ("UPDATE profile SET cats = cats+1 WHERE name = 'Fred'");
s.close (); // close statement
System.out.println ("Number of rows updated: " + count);
IV IT
Using placeholders
Placeholders enable us to avoid writing data values literally into SQL statements.
Using this approach, we write the statement using placeholders which is a special characters
that indicate where the values go. One common placeholder character is ?.
One of the benefits of using placeholders is that parameter binding operations
automatically handle escaping of characters such as quotes and backslashes.
A second benefit of placeholders is that we can prepare a statement in advance
and then reuse it by binding different values to it each time its executed.
IV IT
PERL
To use placeholders in Perl DBI scripts, put a ? in our SQL statement string at each
location where we want to insert a data value, and then bind the values to the statement.
We can bind values by passing them to do( ) or execute( ), or by calling a DBI method
specifically intended for placeholder substitution.
For example
my $sth = $dbh->prepare ("INSERT INTO profile VALUES(?,?,?,?,?)");
my $count = $sth->execute ("De'Mont", "1973-01-12", undef, "eggroll", 4);
RUBY
Ruby DBI uses ? as the placeholder character in SQL statements and nil as the value
to use for binding an SQL NULL value to a placeholder. First we pass the statement string to
prepare to get a statement handle, and then use that handle to invoke execute with the data
values:
sth = dbh.prepare("INSERT INTO profile VALUES(?,?,?,?,?)")
count = sth.execute("De'Mont", "1973-01-12", nil, "eggroll", 4)
PHP
The PEAR DB module allows placeholders to be used with the query( ) method that
executes SQL statements, or we can use prepare( ) to prepare a statement, and execute( ) to
supply the data values and execute the prepared statement. PEAR DB uses ? as the
placeholder marker in SQL statements and the PHP NULL as the value to use when binding
an SQL NULL value to a placeholder.
For example
$stmt =& $conn->prepare ("INSERT INTO profile VALUES(?,?,?,?,?)");
if (PEAR::isError ($stmt))
die ("Oops, statement preparation failed");
$result =& $conn->execute ($stmt, array ("De'Mont","1973-01-12",NULL,"eggroll",4));
if (PEAR::isError ($result))
die ("Oops, statement execution failed");
Python
Pythons MySQLdb module implements placeholders using format specifiers in the
SQL statement string. To use placeholders, invoke the execute( ) method with two
IV IT
arguments: a statement string containing format specifiers and a sequence containing the
values to bind to the statement string.
cursor = conn.cursor ()
cursor.execute ("INSERT INTO profile VALUES(%s,%s,%s,%s,%s)", ("De'Mont", "197301-12", None, "eggroll", 4))
Java
JDBC provides support for placeholders if we use prepared statements. To use a
prepared statement, create a PreparedStatement object by passing a statement string
containing ? place holder characters to our connection objects prepareStatement( ) method.
Then bind our data values to the statement using setXXX ( ) methods. Finally, execute the
statement by calling executeUpdate( ), executeQuery( ), or execute( ) with an empty
argument list.
Here is an example that uses executeUpdate( ) to issue an INSERT statement
PreparedStatement s;
int count;
s = conn.prepareStatement ("INSERT INTO profile VALUES(?,?,?,?,?)");
s.setString (1, "De'Mont"); // bind values to placeholders
s.setString (2, "1973-01-12");
s.setNull (3, java.sql.Types.CHAR);
s.setString (4, "eggroll");
s.setInt (5, 4);
count = s.executeUpdate ();
s.close (); // close statement
IV IT
Perl
Perl DBI represents NULL values using undef. Its easy to detect such values using
the defined( ) function. For example
IV IT
IV IT
[ALL | DISTINCT]
IV IT
A WHERE clause can test multiple conditions and different conditions can test different
columns. For example
IV IT
To avoid this problem, we can give an output column a name of our own choosing, use
an AS name clause to specify a column alias. For example
IV IT
We cannot refer to column aliases in a WHERE clause. Thus, the following statement is
Illegal.
mysql> SELECT t, srcuser, dstuser, size/1024 AS kilobytes FROM mail WHERE kilobytes > 500;
IV IT
That result is heavily redundant. Adding DISTINCT to the query removes the duplicate
rows, producing a set of unique values. For example
IV IT
Sometimes its useful to map NULL values onto some other distinctive value that has
more meaning in the context of our application. For example If NULL id values in the taxpayer
table mean unknown, we can display that fact by using IF( ) to map NULL onto the string
Unknown.
IV IT
This statement names multiple columns in the ORDER BY clause to sort rows by host,
and then by user within each host:
To sort a column in reverse (descending) order, add the keyword DESC after its name in
the ORDER BY clause for example
IV IT
IV IT
Answering questions about first or last, largest or smallest, newest or oldest, least or more
technique is common in web applications for displaying a large search result across
several pages.
To select the first n rows of a query result, add LIMIT n to the end of your SELECT statement:
A more common technique is to use ORDER BY to sort the result set. Then we can use LIMIT
to find smallest and largest values. For example
IV IT
The two-argument form of LIMIT also makes it possible to partition a result set into smaller
sections. For example
IV IT
Strings can be case sensitive, which can affect the outcome of string operations.
We can apply pattern-matching operations to look for strings that have a certain structure.
Types of Strings
MySQL can operate on regular strings or binary strings. "Binary" in this context has little
to do with the presence of non-ASCII values. There are two types of Binary Strings.
Binary data may contain bytes that lie outside the usual range of printable ASCII
characters.
A binary string in MySQL is one that MySQL treats as case sensitive in comparisons.
For binary strings, the characters A and a are considered different. For non-binary strings,
they're considered the same.
A binary column type is one that contains binary strings. Some of MySQL's column types are
binary (case sensitive) and others are not.
IV IT
IV IT
IV IT
IV IT
For LEFT( ) and RIGHT( ), the second argument indicates how many characters to return
from the left or right end of the string. For MID( ), the second argument is the starting position of
the substring and the third argument indicates how many characters to return.
The SUBSTRING( ) function takes a string and a starting position, returning everything
to the right of the position.
To combine strings we can use the CONCAT( ) function. It concatenates all its arguments and
returns the result
IV IT
IV IT
We can use these characters to create patterns that match a wide variety of values.
IV IT
For example
IV IT
String comparisons are case sensitive only if at least one of the operands is a binary
string. To control case sensitivity in string comparisons, use the following techniques:
To make a string comparison case sensitive that normally would not be, cast (convert)
IV IT
To make a string comparison not case sensitive that normally would be, convert both
To perform a search using the index, use MATCH( ) to name the indexed column and
AGAINST( ) to specify what text to look for. For example
SELECT id, MATCH(title) AGAINST ('python threading') AS score FROM entries
IV IT
represent the century, year within century, month, and day parts of the date.
TIME values are represented as in hh:mm:ss format, where hh, mm, and ss are the
hh:mm:ss format.
TIMESTAMP values also include date and time parts, but are represented as strings in
CCYYMMDDhhmmss format.
IV IT
For example
IV IT
IV IT
CURRENT_TIMESTAMP
and
SYSDATE(
are
synonyms
for
NOW(
).
IV IT
IV IT
Another way to obtain individual parts of temporal values is to use the EXTRACT( )
function. The keyword indicating what to extract should be a unit specifier such as YEAR,
MONTH, DAY, HOUR, MINUTE, or SECOND.
IV IT
IV IT
Here, unit is the interval unit and val is an expression indicating the number of units. Some of
the common unit specifiers are YEAR, MONTH, DAY, HOUR, MINUTE, and SECOND.
For example
IV IT
IV IT
column-Name
It refers to the names visible from the SelectItems in the underlying query of the
SELECT statement. The column-Name that we specify in the ORDER BY clause
does not need to be the SELECT list.
ColumnPosition
An integer that identifies the number of the column in the SelectItems in the
underlying query of the SELECT statement. If we want to order by a column position,
that column must be specified in the SELECT list.
Expression
A sort key expression, such as numeric, string, and datetime expressions. Expression
can also be a row value expression such as a scalar sub query or case expression.
1
IV IT
ASC
It specifies that the results should be returned in ascending order. If the order is not
specified, ASC is the default.
DESC
It specifies that the results should be returned in descending order.
For example
The opposite (or reverse) of ascending order is descending order, specified by adding
DESC after the sorted column's name.
To more fully control output order, we can specify a multiple-column sort by listing
each column to use for sorting, separated by commas. The following query sorts in ascending
order by name and by trav_date within the rows for each name
2
IV IT
We can also name the columns by their positions within the output column list or by
using aliases. Positions within the output list begin with 1. The following query sorts results
by the third output column.
If an output column has an alias, we can refer to the alias in the ORDER BY clause
IV IT
The ORDER BY clause also allows us to sort the result set based on an expression.
We have to put the expression that calculates the values in the ORDER BY clause. For
example
For example
4
IV IT
IV IT
FIELD(value,str1,str2,str3,str4)
FIELD( ) cal also takes a variable-length argument list. If value is NULL or none of the
values match, FIELD( ) returns 0.
IV IT
Generating Summaries
Database systems are useful for storing and retrieving records, but they also can
generate the summarized information for the data in more concise form. Summaries are
useful when we want the overall picture rather than the details. They're also typically more
readily understood than a long list of records.
The type of summaries we can perform may depend on the kind of data we're working
with. A counting summary can be generated from any kind of values, whether they are
numbers, strings, or dates. For summaries that involve sums or averages, only numeric values
can be used.
Summary operations in MySQL involve the following SQL constructs:
To compute a summary value from a set of individual values, use one of the functions
known as aggregate functions. These are so called because they operate on
aggregates (groups) of values. Aggregate functions include COUNT( ), which counts
records or values in a query result; MIN( ) and MAX( ), which find smallest and
largest values; and SUM( ) and AVG( ), which produce sums and means of values.
These functions can be used to compute a value for the entire result set, or with a
GROUP BY clause to group the rows into subsets and obtain an aggregate value for
each one.
To obtain a list of unique values, use SELECT DISTINCT rather than SELECT.
To count how many distinct values there are, use COUNT(DISTINCT) rather than
COUNT( ).
IV IT
13 |
+----------+
1 row in set (0.01 sec)
+----------+
|
5|
+----------+
mysql>SELECT COUNT(DISTINCT DEPTNO) DEPTS FROM employee_tbl;
+----------+
| DEPTS
+----------+
|
4|
+----------+
IV IT
IV IT
IV IT
For example
IV IT
IV IT
If we use execute ( ), that method returns true or false to indicate whether or not the statement
produces a result set.
IV IT
IV IT
IV IT
IV IT
PHP Example:
After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling
mysql_insert_id( ).