Mysql Notes
Mysql Notes
as MySQL.
MySQL 3.11 was released few months later by solaris.
GPL community take care of the rest.
TcX spun off MySQL AB, today is the sole owner of the MySQL server source
code and trademark and is responsible for maintenance, marketing and further
development.
Features:
Three fundamental principles:
Performance
Reliability
Ease of use
Speed:
The time takes to execute a query and return the results to the caller.
Reliability:
MySQL's large user base assists in rapidly locating and resolving bugs and in
testing the software in a variety of environments.
Ease of use:
Large number of free online tutorials, a knowledgeable developer community and
fair number of books to make easy.
Multi user support:
MySQL is a full multiuser system multiple clients can access and use one or more
databases simultaneously.Powerful and flexible privilege system to protect access
to sensitive data.
Scalability:
MySQL can handle extermely large and complex databases without too much of a
performance drop.
Portability:
MySQL is available for both UNIX and non-UNIX operating systems include
Solaris, FreeBSD, OS/2, MacOs and Windows.
It runs on a range of architectures, including Intel x86, Alpha, SPARC, PowerPC,
and IA64.
Compliance with Existing Standards:
MySQL 4.0 supports most of the important features of the ANSI SQL-99 standard.
MySQL extends the ANSI standard with custom extensions, functions and data
types.
Internationalization: Used by millions in countries across the globe, so MySQL
supports number of important character stes with full unicode support.
Wide application support: MySQL exposes API to many programming
languages, making possible to write database-driven application language of user
choice.
2
The storage manager writes to disk all of the data in the user tables, indexes
and logs as well as internal systems.
The Query Cache: If a query returns a given set of records, repeating the
same query should return the same set of records unless the underlying data
has somehow changed.
The MySQL engine uses an extremely efficient result set caching
mechanism, known as query cache.
The Buffer Manager
This subsystem handles all memory management issues between requests
for data by the query engine and storage manager.
MySQL makes aggressive use of memory to cache result sets that can be
returned as-is rather than making duplicate requests to the storage manager,
this cache is maintained in the buffer manager.
If any new data is needed, it's requested from the storage manager and
placed in the buffer before then being sent to the query engine.
The Transaction Manager
Transaction manager is to facilitate concurrency in data access.
This subsystem provides a locking facility to ensure the multiple
simultaneous users access the data in a consistent way, without damaging
the data.
Transaction control takes place via the lock manager subcomponent, which
places and release locks on various objects being used in transactions.
The Recovery Manager
The recovery manager's job is to keep copies of data for retrieval later, in
case of loss of data.
Only InnoDB and BDB table handlers provide recovery management.
MyISAM handler doesn't have transactional recovery procedures.
Support Components
In addition to five primary subsystems, the MySQL architecture contains the
following two support components.
The Process manager
Function Libraries
MySQL Engine
MySQL supports small, embedded kiosk-style applications as well as the
occasional five billion-record data warehouse.
Connectivity: MySQL is designed on the assumption that the vast majority
of its applications will be running on a TCP/IP network.
TCP/IP is not only highly secure but also common to unix, Windows and
OS/2.
4
2147483646.
DECIMAL: A numeric type with support of floating point or decimal numbers.
DOUBLE: A numeric type for double-precisin floating-point numbers
DATE: A data field in the YYYY-MM-DD format.
TIME: A time field in the HH:MM:SS format
DATETIME: A combined date/time type in the YYYY-MM-DD HH:MM:SS
YEAR: A field specifically for year displays the range 1901 to 2155
TIMESTAMP: A timestamp type, in YYYYMMDDHHMMSS format
CHAR: A string type with maximum size of 255 characters
TEXT: A string type with a maximum size of 65,535 characters
BLOB: A binary type of variable data
ENUM: A string type that can accept one value from previous values
SET: A string type can accept zero or more from previous values.
Setting up Account
MySQL database you need to create an account to use for connecting to the
MySQL server running on a given host.
Use the GRANT statement to set up the MySQL user account
User names, as used by MySQL for authentication purposes.
MySQL user names can be up to 16 characters long.
Adding User Accounts
You can create MySQL accounts in two ways:
By using statements intended for creating accounts, such as CREATE USER
or GRANT
By manipulating the MySQL grant tables directly with statements such as
INSERT, UPDATE, or DELETE.
Account Management Statements
Create User
Drop User
Grant
Rename
Revoke
Set Password
Create User
Description:
The CREATE USER statement creates new MySQL accounts.
Syntax:
CREATE USER user [IDENTIFIED BY [PASSWORD] 'password']
Example:
Drop User
Description:
The DROP USER statement removes one or more MySQL accounts and their
privileges.
Syntax:
DROP USER user [, user] ...
Example:
Table level
Table level privileges are applied to all columns on a given table. These type of
privileges are stored in the table_priv table of the mysql database. EX ?
GRANT ALL ON database_name.table_name and REVOKE ALL ON
database_name.table_name.
Column level
Column level privileges are applied to single column on a given table. These
type of privileges are stored in columns_priv table of mysql database. And at
the time of using REVOKE statement you have to specify the same column
name that were granted.
Routine level
Routine level privileges like CREATE ROUTINE, EXECUTE, ALTER
ROUTING and GRANT privileges are applied to stored routines. These type of
privileges can be granted at global and database level. Except CREATE
ROUTINE, rest of these privileges can be granted at routine level for particular
routines and they are stored in the procs_priv table of mysql database.
Privilege
ALL [PRIVILEGES]
ALTER
ALTER ROUTINE
CREATE
CREATE ROUTINE
CREATE TEMPORARY TABLES
CREATE USER
CREATE VIEW
DELETE
DROP
EXECUTE
FILE
INDEX
INSERT
LOCK TABLES
PROCESS
REFERENCES
RELOAD
REPLICATION CLIENT
REPLICATION SLAVE
8
Meaning
Sets all simple privileges except GRANT OPTION
Enables use of ALTER TABLE
Enables stored routines to be altered or dropped
Enables use of CREATE TABLE
Enables creation of stored routines
Enables use of CREATE TEMPORARY TABLE
Enables use of CREATE USER, DROP USER,
RENAME USER, and REVOKE ALL PRIVILEGES.
Enables use of CREATE VIEW
Enables use of DELETE
Enables use of DROP TABLE
Enables the user to run stored routines
Enables use of SELECT ... INTO OUTFILE and
LOAD DATA INFILE
Enables use of CREATE INDEX and DROP INDEX
Enables use of INSERT
Enables use of LOCK TABLES on tables for which
you have the SELECT privilege
Enables use of SHOW FULL PROCESSLIST
Not implemented
Enables use of FLUSH
Enables the user to ask where slave or master servers
are
Needed for replication slaves (to read binary log
events from the master)
Prepared By, R.Sangeetha AP/CSE
SELECT
SHOW DATABASES
SHOW VIEW
SHUTDOWN
SUPER
UPDATE
USAGE
GRANT OPTION
Grant
Description:
The GRANT statement enables system administrators to grant privileges to
MySQL user accounts.
Example:
GRANT SELECT,INSERT,UPDATE,DELETE ON my_db.* TO 'michael'@'localhost';
Revoke
Description:
The REVOKE statement enables system administrators to revoke privileges
from MySQL accounts.
Example:
mysql> REVOKE ALL PRIVILEGES, GRANT OPTION FROM chand;
Query OK, 0 rows affected (0.01 sec)
Set Password
Description:
The SET PASSWORD statement assigns a password to an existing MySQL
user.
Syntax:
SET PASSWORD [FOR user] = PASSWORD('some password')
Example:
Stopping MySQL
Logout
Starting MySQL
The MySQL server can be started manually from the command line.
To start the mysqld server from the command line, you should start a
console window (or DOS window) and enter this command:
shell> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqld"
The path to mysqld may vary depending on the install location of MySQL
on your system.
Login
To start the mysql program, type myql at your command-line prompt.
If mysql starts up correctly, you'll see a short message, followed by a mysql>
prompt that indicates the program is ready to accept queries.
To illustrate, here's what the welcome message looks like % mysql
Stopping MySQL
You can stop the MySQL server by executing this command:
shell> "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqladmin" u
root shutdown
Logout
To terminate a mysql session, issue a QUIT statement:
mysql> QUIT
You can also terminate the session by issuing an EXIT statement or (under
Unix) by typing Ctrl-D.
RECORD SELECTION TECHNIQUES
Sample Table
11
12
13
14
15
16
17
STRINGS
Eight basic string types
It can be used to store string data ranging from simple one character strings to
large blocks of text or binary data. BLOB Binary Large Object
18
CHAR type
Simplest type.
CHAR type is used for fixedlength
strings must be declared with size specifier in parenthesis.
The declaration CHAR(10) specifies a value 10 characters in length.
The value smaller than the specified length will be right padded with spaces.
The value larger than the specified length will be automatically truncated.
Example
mysql> CREATE TABLE data (alphabet CHAR(10));
mysql> INSERT INTO data VALUES ('abcdefghijklmno');
mysql> INSERT INTO data VALUES ('abc');
The output is
mysql> SELECT alphabet from data;
adcdefghij
abc
VARCHAR
A varient of the CHAR type is the VARCHAR type, which is useful for
variablelength strings;it, too, must be accompanied with a size specifier in
the range of 0 to 255.
CHAR type treat as the exact size for values, while VARCHAR type treats
this as a maximum size for values and uses only the number of bytes
actually needed to store the string.
The TEXT and BLOB types
For the strings greater than 255 characters in length MySQL provides both
BLOB and TEXT types, each with different subtypes depending on the size
19
20
21
22
Strings that contain a particular substring at any position:
You can also use relational operators such as <, <=, >=, and > to compare
strings in lexical order:
24
mysql> SELECT name, name < 'lead', name > 'lead' FROM metal;
| dt
|
+--------------------------+
| 1970-01-01 00:00:00 |
| 1987-03-05 12:30:15 |
| 1999-12-31 09:00:00 |
| 2000-06-04 15:45:30 |
+--------------------------+
TIMESTAMP values include date and time parts, but are represented as strings in
CCYYMMDDhhmmss format.
mysql> SELECT ts FROM timestamp_val;
+---------------------+
| ts
|
+---------------------+
| 19700101000000 |
| 19870305123015 |
| 19991231090000 |
| 20000604154530 |
+----------------------+
How to Display Dates or Times
MySQL displays dates in ISO format if you have not specified the format.
To rewrite datevalues into other formats, use the DATE_FORMAT( ) function,
which takes two arguments: a DATE, DATETIME, or TIMESTAMP value
mysql> SELECT d, DATE_FORMAT(d,'%M%d, %Y') FROM date_val;
+----------------+-----------------------------------------+
|d
| DATE_FORMAT(d,'%M%d, %Y') |
+----------------+-----------------------------------------+
| 1864-02-28 | February 28, 1864
|
| 1900-01-15 | January 15, 1900
|
| 1987-03-05 | March 05, 1987
|
| 1999-12-31 | December 31, 1999
|
| 2000-06-04 | June 04, 2000
|
+------------+-------------------------------------------+
26
27
+--------------------------+-----------------+----------------+
| NOW( )
| CURDATE( ) | CURTIME( ) |
+--------------------------+-----------------+-----------------+
| 2002-07-15 10:59:30 | 2002-07-15 | 10:59:30
|
+--------------------------+------------------+----------------+
Decomposing Dates and Times Using Formatting Functions
Use a formatting function such as DATE_FORMAT( ) or TIME_FORMAT(
) with a format string.
mysql> SELECT dt,
-> DATE_FORMAT(dt,'%Y') AS year,
-> DATE_FORMAT(dt,'%d') AS day,
-> TIME_FORMAT(dt,'%H') AS hour,
-> TIME_FORMAT(dt,'%s') AS second
-> FROM datetime_val;
28
29
30
32
33
34
Mixed-order sorting:
mysql> SELECT * FROM driver_log ORDER BY name DESC,
trav_date;
35
36
37
38
39
Using CONCAT( ):
mysql> SELECT last_name, first_name FROM name
-> ORDER BY last_name, first_name;
40
To put them at the end instead, introduce an extra ORDER BY column that
maps NULL values to a higher value than non-NULL values:
mysql> SELECT val FROM t ORDER BY IF(val IS NULL,1,0), val;
42
To perform a case-sensitive sort for strings that are not case sensitive (such
as those in the tstr column) cast the sort column to binary-string form using
the BINARY keyword:
mysql> SELECT tstr FROM textblob_val ORDER BY BINARY tstr;
Another possibility is to convert the output column to binary and sort that:
mysql> SELECT BINARY tstr FROM textblob_val ORDER BY 1;
Using CAST( ):
You can also use the CAST( ) function that is available as of MySQL 4.0.2:
mysql> SELECT tstr FROM textblob_val ORDER BY CAST(tstr AS BINARY);
8. Date-Based Sorting:
Sort using a date or time column type, ignoring parts of the values that
are irrelevant if necessary.
mysql> SELECT * FROM temporal_val;
To put these items in calendar order, sort them by month, then by day within
month:
44
NOTE: If a table represents dates using separate year, month, and day
columns, calendar sorting requires no date-part extraction. Just sort the
relevant columns directly.
10. Sorting by Day of Week:
To sort in day-of-week order.
Use DAYOFWEEK( ) to convert a date column to its numeric day of
week value.
mysql> SELECT DAYNAME(date) AS day, date, description
-> FROM event
-> ORDER BY DAYOFWEEK(date);
If you want to sort in day-of-week order, but treat Monday as the first day of the
week and Sunday as the last, you can use a the MOD( ) function to map Monday to
0, Tuesday to 1, ...,Sunday to 6:
mysql> SELECT DAYNAME(date), date, description
-> FROM event
-> ORDER BY MOD(DAYOFWEEK(date) + 5, 7);
Using TIME_TO_SEC( ):
mysql> SELECT * FROM mail ORDER BY TIME_TO_SEC(t);
12. Sorting Using Substrings of Column Values:
To sort a set of values using one or more substrings of each value.
Extract the hunks you want and sort them separately.
This is an application of sorting by expression value.
13. Sorting by Fixed-Length Substrings:
To sort using parts of a column that occurs at a given position within the
column.
Pull out the parts you need with LEFT( ), MID( ), or RIGHT( ) and sort
them.
mysql> SELECT * FROM housewares;
46
using SUBSTRING_INDEX(str,c,n):
It searches into a string str for the n-th occurrence of a given character c
and returns everything to the left of that character.
For example, the following call returns 13-478:
SUBSTRING_INDEX('13-478-92-2','-',2)
If n is negative, the search for c proceeds from the right and returns the
rightmost string.
This call returns 478-92-2:
SUBSTRING_INDEX('13-478-92-2','-',-3)
mysql> SELECT
-> id,
-> SUBSTRING_INDEX(SUBSTRING_INDEX(id,'-',2),'-',-1) AS segment2,
-> SUBSTRING_INDEX(SUBSTRING_INDEX(id,'-',4),'-',-1) AS segment4
-> FROM housewares3;
49
50
'Thursday','Friday','Saturday')
);
mysql> INSERT INTO weekday (day) VALUES('Monday'),('Friday'),
-> ('Tuesday'), ('Sunday'), ('Thursday'), ('Saturday'), ('Wednesday');
mysql> SELECT day, day+0 FROM weekday;
52
Now we want to find the customers that have an OrderPrice value higher
than the average OrderPrice value.
We use the following SQL statement:
SELECT Customer FROM Orders
WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders);
The result-set will look like this:
53
which is the number of unique customers (Hansen, Nilsen, and Jensen) in the
"Orders" table.
The FIRST() Function
The FIRST() function returns the first value of the selected column.
SQL FIRST() Syntax
SELECT FIRST(column_name) FROM table_name;
SQL FIRST() Example
Now we want to find the first value of the "OrderPrice" column.
We use the following SQL statement:
SELECT FIRST(OrderPrice) AS FirstOrderPrice FROM Orders;
Tip: Workaround if FIRST() function is not supported:
SELECT OrderPrice FROM Orders ORDER BY O_Id LIMIT 1;
The result-set will look like this:
USING SEQUENCES
INTRODUCTION
A sequence is a set of integers 1, 2, 3 ... that are generated in order on
demand. Sequences are frequently used in databases because many applications
require each row in a table to contain a unique value, and sequences provide an
easy way to generate them.
MySQL Sequences
Using AUTO_INCREMENT To Set Up a SequenceColumn
One of the useful properties of an AUTO_INCREMENT column is that you
don't have to assign its value by yourselfMySQL does for you.
CREATE TABLE insect
(name VARCHAR(30) NOT NULL,
date DATE NOT NULL,
origin VARCHAR(30) NOT NULL );
Second, you can omit the id column from the INSERT statement entirely
mysql> INSERT INTO insect (name,date,origin) VALUES
-> ('butterfly','2001-09-10','garden'),
-> ('ant','2001-09-10','back yard'),
-> ('ant','2001-09-10','back yard'),
-> ('millbug','2001-09-10','under rock');
mysql> SELECT * FROM insect ORDER BY id;
58
Alternatively, you can create the table and then set the initial sequence value
with ALTER TABLE:
59
60
In this 10-part weekly series of articles, I'll provide a hands-on look at what's
involved in building a database-driven Web site. We'll be using two new tools for
this: the PHP scripting language and the MySQL relational database. If your Web
host provides PHP/MySQL support, you're in great shape. If not, we'll be looking
at the set-up procedures under Unix and Windows, so don't sweat it.
These articles are aimed at intermediate or advanced Web designers looking
to make the leap into server-side programming. You'll be expected to be
comfortable with HTML, as I'll be making use of it without explanation. A teensy
bit of JavaScript may serve us well at some point, but I'll be sure to keep it simple
for the uninitiated.
By the end of this series, you can expect to have a grasp of what's involved
in setting up and building a database-driven Web site. If you follow along with the
examples, you'll also learn the basics of PHP (a server-side scripting language that
allows you to do a lot more than access a database easily) and Structured Query
Language (SQL -- the standard language for interacting with relational databases).
Most importantly, you'll come away with everything you need to get started on
your very own database-driven site in no time!
Part 1: Installation
Hi there, and welcome to the first in SitePoint.com's ten-part series on
building a database-driven Web site! For the next few months, it will be my job to
guide you as you take your first steps beyond the HTML-and-JavaScript world of
client-side site design. Together we'll learn everything that's needed to build the
kind of large, content-driven sites that are so successful today, but which can be a
real headache to maintain if they aren't done right.
Before we get started, we need to gather together the tools we'll need for the
job. In this first article, we'll download and set up the two software packages we'll
be using: PHP and MySQL.
PHP is a server-side scripting language. You can think of it as a "plug-in"
for your Web server that will allow it to do more than just send plain Web pages
when browsers request them. With PHP installed, your Web server will be able to
read a new kind of file (called a "PHP script") that can do things like retrieve upto-the-minute information from a database and insert it into a Web page before
sending it to the browser that requested it. PHP is completely free to download and
use.
To retrieve information from a database, you first need to have a database.
That's where MySQL comes in. MySQL is a relational database management
system, or RDBMS. Exactly what role it plays and how it works we'll get into
later, but basically it's a software package that is very good at organizing and
managing large amounts of information. MySQL also makes that information
really easy to get at using server-side scripting languages like PHP. MySQL is free
61
for non-commercial use on most Unix-based platforms, like Linux. MySQL for
Windows 9x/NT/2000 costs about US$200 to buy, but you can download an older
version for free if you just want to try it out. For our purposes, the older version
will serve just fine, but if you find MySQL for Windows useful and you decide to
use it on one of your own sites, you should pay for it.
If you're lucky, your current Web host may already have installed MySQL
and PHP on your Web server for you. If that's the case, much of this article will not
apply to you, and you can skip straight to If Your Web Host Provides PHP and
MySQL to make sure everything is ship shape.
Everything we'll discuss in this article series may be done on a Windows- or
Unix-based server. Depending on which type of server you'll be using, the
installation procedure will be different. The next section deals with installation on
a Windows-based Web server. The section after that deals with installation under
Linux (and other Unix-based platforms). Unless you're especially curious, you
should only need to read the section that applies to you.
Part 2: Getting Started with MySQL
Hi there, and welcome back! Last week, we went through the process of
installing and setting up two software programs: PHP and MySQL. This week,
we'll be concentrating on the latter by learning how to work with MySQL
databases using Structured Query Language (SQL).
An Introduction to Databases
As I explained briefly last week, PHP is a server-side scripting language that
lets you insert instructions into your Web pages that your Web server software (be
it Apache, Personal Web Server, or whatever) will execute before sending those
pages to a browser that requests them. In a brief example, I showed how it was
possible to insert the current date into a Web page every time it was requested.
Now thats all well and good, but things really get interesting when a
database is added to the mix. A database server (in our case, MySQL) is a program
that can store large amounts of information in an organized format that is easily
accessible from scripting languages like PHP. For example, you could tell PHP to
look in the database for a list of jokes that you'd like to appear on your Web site.
In this example, the jokes would be stored entirely in the database. The
advantage of this would be twofold. First, instead of having to write an HTML file
for each of your jokes, you could write a single PHP file designed to fetch any joke
out of the database and display it. Second, to add a joke to your Web site would
just be a matter of adding the joke to the database. The PHP code would take care
of the rest by automatically displaying the new joke along with the rest when it
fetched the list of jokes from the database.
Lets run with this example as we look at how data is stored in a database. A
database is composed of one or more 'tables', each of which contains a list of
62
'things'. For our joke database, we would probably start with a table called "jokes"
which would contain a list of jokes. Each table in a database has one or more
columns, or fields. Each column holds a certain piece of information about each
"thing" in the database. Returning to our example, our "jokes" table might have
columns for the text of the jokes and the dates the jokes were added to the
database. Each joke that we stored in this table would then be said to be a 'row' in
the table. To see where all this terminology comes from, have a look at what this
table actually looks like:
Notice that, in addition to columns for the joke text ("JokeText") and the
date of the joke ("JokeDate"), I included a column named "ID". The function of
this column is to assign a unique number to each joke so we have an easy way to
refer to them and to keep track of which joke is which.
So to review, the above is a three-column table with two rows (or entries).
Each row in the table contains a joke's ID, its text, and the date of the joke. With
this basic terminology under our belts, we're ready to get started using MySQL.
Part 3: Publishing MySQL Data on the Web
This is it -- the stuff you signed up for! This is the week we take information stored
in a database and display it on a Web page for all to see. So far we've installed and
learned the basics of MySQL, a relational database engine, and PHP, a server-side
scripting language. In this week's installment, we see how to use these two new
tools together to create a true database-driven Web site!
A Look Back at First Principles
Before we leap forward, it's worth a brief look back to remind ourselves of
the goal we are working toward. We have two powerful, new tools at our disposal:
the PHP scripting language, and the MySQL database engine. It's important to
understand how these two are going to fit together.
The whole idea of a database-driven Web site is to allow the content of the
site to reside in a database, and for that content to be dynamically pulled from the
database to create Web pages featuring it for people using a regular Web browser
to view. So on one end of the system you have a visitor to your site using a Web
browser, loading http://www.yoursite.com/, and expecting to view a standard
HTML Web page. On the other end you have the content of your site sitting in one
or more tables in a MySQL database that only understands how to respond to SQL
queries (commands).
The PHP scripting language is the go-between that speaks both languages.
Using PHP, you can write the presentation aspects of your site (the fancy graphics
and page layouts) as "templates" in regular HTML. Where the content belongs in
those templates, you use some PHP code to connect to the MySQL database and -using SQL queries just like those you used to create a table of jokes in Part Two -retrieve and display some content in its place.
63
Just so it's clear and fresh in your mind, this is what will happen when
someone visits a page on our database-driven Web site:
The visitor's Web browser asks for the Web page using a standard URL.
The Web server software (Apache, IIS, or whatever) recognizes that the
requested file is a PHP script, and so interprets it using its PHP plug-in
before responding to the page request.
Some PHP commands (which we have yet to learn) connect to the MySQL
database and request the content that belongs in the Web page.
The MySQL database responds by sending the requested content to the
PHP script.
The PHP script stores the content into one or more PHP variables, then
uses the now familiar echo function to output it as part of the Web page.
The PHP plug-in finishes up by handing a copy of the HTML it has created
to the Web server.
The Web server sends the HTML to the Web browser as it would a plain
HTML file, except instead of coming directly from an HTML file, the page
is the output provided by the PHP plug-in.
Connecting to MySQL with PHP
Before we can get content out of our MySQL database for inclusion in our
Web page, we must first know how to establish a connection to MySQL. Back in
Part Two, we used a program called mysql that allowed us to make such a
connection. PHP has no need of any special program, however; support for
connecting to MySQL is built right into the language. The following PHP function
call establishes the connection:
mysql_connect(<address>, <username>, <password>);
Where <address> is the IP address or hostname of the computer on which
the MySQL server software is running ("localhost" if running on the same
computer as the Web server software), and <username> and <password> are the
same MySQL user name and password you used to connect to the MySQL server
in Part Two.
You may or may not remember that functions in PHP usually return (output)
a value when they are called. Don't worry if this doesn't ring any bells for you -- it's
a detail that we glossed over when originally discussing functions. In addition to
doing something useful when they are called, most functions output a value, and
that value may be stored in a variable for later use. The mysql_connect function
shown above, for example, returns a number that identifies the connection that has
been established. Since we intend to make use of the connection, we should hold
onto this value. Here's an example of how we might connect to our MySQL server.
$dbcnx = mysql_connect("localhost", "root", "mypasswd");
64
As described above, the values of the three function parameters may differ
for your MySQL server. What's important to see here is that the value returned by
mysql_connect (which we'll call a connection identifier) is stored in a variable
named $dbcnx.
Since the MySQL server is a completely separate piece of software, we must
consider the possibility that the server is unavailable, or inaccessible due to a
network outage, or because the username/password combination you provided is
not accepted by the server. In such cases, the mysql_connect function doesn't
return a connection identifier (since no connection is established). Instead, it
returns false. This allows us to react to such failures using an if statement:
$dbcnx = @mysql_connect("localhost", "root", "mypasswd");
if (!$dbcnx) {
echo( "<P>Unable to connect to the " .
"database server at this time.</P>" );
exit();
}
There are three new tricks in the above code fragment. First, we have placed
a @ symbol in front ofthe mysql_connect function. Many functions, including
mysql_connect, automatically display ugly error messages when they fail. Placing
a @ symbol in front of the function name tells the function to fail silently, allowing
us to display our own, friendlier error message.
Next, we put an exclamation point in front of the $dbcnx variable in the
condition of the if statement. The exclamation point is the PHP "negation
operator", which basically flips a false value to true, or a true value to false. Thus,
if the connection fails and mysql_connect returns false, ! $dbcnx will evaluate to
true, and cause the statements in our if statement to be executed. Alternatively, if a
connection was made, the connection identifier stored in $dbcnx will evaluate to
true (any number other than zero is considered "true" in PHP), so !$dbcnx will
evaluate to false, and the statements in the if statement will not be executed.
The last new trick is the exit function, which is the first example of a
function that takes no parameters that we have encountered. All this function does
is cause PHP to stop reading the page at this point. This is a good response to a
failed database connection, since in most cases the page will be unable to display
any useful information without that connection.
As in Part Two, the next step once a connection is established is to select the
database you want to work with. Let's say we want to work with the joke database
we created in Part Two. The database we created was called jokes. Selecting that
database in PHP is just a matter of another function call:
mysql_select_db("jokes", $dbcnx);
65
Example:
query = "SELECT name, foods FROM profile"
print "Query: ", query
cursor = conn.cursor ( )
cursor.execute (query)
# metadata information becomes available at this point ...
print "Number of rows:", cursor.rowcount
if cursor.description == None: # no result set
ncols = 0
else:
ncols = len (cursor.description)
print "Number of columns:", ncols
if ncols == 0:
print "Note: query has no result set"
for i in range (ncols):
col_info = cursor.description[i]
# print name, then other information
print "--- Column %d (%s) ---" % (i, col_info[0])
print "Type: ", col_info[1]
print "Display size: ", col_info[2]
print "Internal size:", col_info[3]
print "Precision: ", col_info[4]
print "Scale: ", col_info[5]
print "Nullable: ", col_info[6]
cursor.close
Output:
Query: SELECT name, foods FROM profile
Number of rows: 10L
Number of columns: 2
--- Column 0 (name) --Type: 254
Display size: 7
Internal size: 20
Precision: 20
Scale: 0
Nullable: 0
--- Column 1 (foods) --Type: 254
Display size: 21
Internal size: 42
Precision: 42
68
Scale: 0
Nullable: 1
In JAVA
Example:
String query = "SELECT name, foods FROM profile";
System.out.println ("Query: " + query);
Statement s = conn.createStatement ( );
s.executeQuery (query);
ResultSet rs = s.getResultSet ( );
ResultSetMetaData md = rs.getMetaData ( );
// metadata information becomes available at this point ...
int ncols = md.getColumnCount ( );
System.out.println ("Number of columns: " + ncols);
if (ncols == 0)
System.out.println ("Note: query has no result set");
for (int i = 1; i <= ncols; i++) // column index values are 1-based
{
System.out.println ("--- Column " + i
+ " (" + md.getColumnName (i) + ") ---");
System.out.println ("getColumnDisplaySize: " +
md.getColumnDisplaySize(i));
System.out.println ("getColumnLabel: " + md.getColumnLabel (i));
System.out.println ("getColumnType: " + md.getColumnType (i));
System.out.println ("getColumnTypeName: " + md.getColumnTypeName(i));
getColumnType: 1
getColumnTypeName: CHAR
getPrecision: 0
getScale: 0
getTableName: profile
isAutoIncrement: false
isNullable: 0
isCaseSensitive: true
isSigned: false
--- Column 2 (foods) --getColumnDisplaySize: 42
getColumnLabel: foods
getColumnType: 1
getColumnTypeName: CHAR
getPrecision: 0
getScale: 0
getTableName: profile
isAutoIncrement: false
isNullable: 1
isCaseSensitive: true
isSigned: false
In Perl
In DBI scripts, the affected-rows count is returned by do( ) or by execute( ),
depending on how you execute the query:
# execute $query using do( )
my $count = $dbh->do ($query);
# report 0 rows if an error occurred
printf "%d rows were affected\n", (defined ($count) ? $count : 0);
# execute query using prepare( ) plus execute( )
my $sth = $dbh->prepare ($query);
my $count = $sth->execute ( );
printf "%d rows were affected\n", (defined ($count) ? $count : 0);