Even the zsh shell includes a set of predefined shell functions for usingMySQL command line client programs mysql, mysqlshow, mysqldump,mysqldiff, and mysqladmin.. ■■ libdbi-dbd-mysql— I
Trang 1■■ mod_vhost_mysql2— Maintains virtual host configurations in a
MySQL database (2.x)
■■ mod_vhs— Stores virtual host configuration data in a MySQL
database (2.x)
N OT E Chapters 23 and 24 discuss Apache and using Apache modules in detail.
PHP, an extremely popular Web scripting language, has at least two differentAPIs for using MySQL in PHP-based applications Python, a popular and easy-to-use object-oriented programming language, has a module that incorporatesMySQL into Python-based programs in a standard, uniform fashion Other pro-gramming languages also incorporate MySQL via modules, loadable libraries,
or APIs Even the zsh shell includes a set of predefined shell functions for usingMySQL command line client programs (mysql, mysqlshow, mysqldump,mysqldiff, and mysqladmin)
If you’re convinced that MySQL is the database you want to use, it will help
to make sure it is installed Use the rpmquery command to see if the packagesmysql-server, mysql, and mysql-devel are installed You can use the fol-lowing commands to see if these packages are installed:
N OT E Chapter 30 explains how to install RPM-based software packages.
Other MySQL-related packages that might be installed or that you mightwant to install include:
■■ mod_auth_mysql— Provides an Apache module that uses MySQL tocontrol access to Web pages
Trang 2■■ libdbi-dbd-mysql— Installs a device-independent database driverfor use by programs using ldbdbi
■■ php-mysql— Contains a PHP module that enables PHP to connect toand manipulate MySQL databases
■■ mysql-bench— Includes a suite of benchmark tests and test data touse for benchmarking MySQL’s performance on your system
Securing the MySQL Installation
Part of the MySQL installation process installs a script to create a database(named mysql) of administrative tables that handle access control and data-base privileges, a test database (imaginatively named test), an administra-tive user for the database (named root), and an anonymous user (namedanonymous) This script is executed the first time you start the mysqld data-base daemon Neither the root account nor the anonymous account is pass-word-protected, so the first thing you want to do is create a password for theroot account In our opinion, naming the administrative user root was a poorchoice because it is quite confusing in that the superuser on your system is alsonamed root This user has superuser privileges on the database, so root is a
natural but unfortunate choice Just so there’s no confusion, MySQL’s root user is not the same as the system’s root user.
Before attempting to change any passwords, verify that the database is ning One way to do so is to become the (system) root user and use the serviceutility:
run-# service mysqld status
mysqld (pid 24900) is running
If mysqld, the MySQL server daemon, isn’t running, you can start it usingthe usual command:
# service mysql start
Starting MySQL: [ OK ]
Another way to do test the server, one that doesn’t require root access, is touse the mysqladmin and/or mysqlshow commands to see whether theserver is running and responding to connections For example, the followingmysqladmincommand shows the server version:
$ mysqladmin version
mysqladmin Ver 8.23 Distrib 3.23.58, for redhat-linux-gnu on i386 Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This software comes with ABSOLUTELY NO WARRANTY This is free software,
Trang 3Server version 3.23.58 Protocol version 10 Connection Localhost via UNIX socket UNIX socket /var/lib/mysql/mysql.sock Uptime: 2 min 55 sec
Threads: 1 Questions: 2 Slow queries: 0 Opens: 6 Flush tables: 1 Open tabl es: 0 Queries per second avg: 0.011
The output might differ slightly, depending on the version of MySQLinstalled The mysqlshow command can be used to get information about theserver, such as what databases it is serving and the tables that exist in thosedatabases For example, a bare mysqlshow command displays the availabledatabases:
$ mysqlshow
+ -+
| Databases | + -+
| mysql |
| test | + -+
You’ll learn more about the MySQL client programs in the next section.After you’ve established that MySQL is running, set the passwords for theMySQL root account using the mysqladmin commands shown in the follow-ing listing (you must be root to execute these commands):
# mysqladmin -u root password “sekritword”
# mysqladmin -u root -h hostname “sekritword”
The first command sets the password for MySQL’s root user when it is necting from localhost, to sekritword The second command changes thepassword for the MySQL when root is connecting from the hostname specified
con-by hostname What’s the difference? MySQL distinguishes connections con-by the
username and by the host from which users are connecting By default, MySQL
assumes that a user is connecting from localhost (that is, the IP address127.0.0.1), so username@localhost needs a password However, in mostcases, the localhost also has a fully qualified domain name (that is, a hostname),such as datagrunt.example.com, and MySQL considers such a connectiondistinct Accordingly, username@hostname (say, username@datagrunt.example.com) also needs a password.
Use the following command to see the results of your commands:
$ mysql -e “select host, user, password from mysql.user” -u root -p
Enter password:
Trang 4| host | user | password | + -+ -+ -+
| localhost | root | 5d2e19393cc5ef67 |
| datagrunt.example.com | root | 5d2e19393cc5ef67 |
| localhost | | |
| datagrunt.example.com | | | + -+ -+ -+
You can see that the password for the root use has been set You can also seethat the password you entered has been encrypted The -u root argument tothe mysql command specifies the username; -p tells mysql to show a pass-word prompt You should enter the password you used when you set the pass-word as shown earlier
Notice that a similar set of accounts exists for a user with no name; this is theanonymous user mentioned previously You need to decide at this point if youwant to permit anonymous access to the server If you do, you can leave theaccounts without a password or you can set a password Alternatively, you candelete the anonymous accounts entirely Whether you leave the accounts intact
is a matter of local security policy We leave them in place and don’t set words on them for testing applications during development and delete them
pass-on productipass-on systems The anpass-onymous user has limited privileges tially, read-only), but it isn’t a good idea to have unsecured accounts on a pro-duction system
(essen-If you choose to set a password for the anonymous accounts, use the mands shown in the following example:
com-# mysql -u root -p
Enter password:
mysql> set password for ‘’@localhost = password(‘magicword’);
Query OK, 0 rows affected (0.00 sec)
mysql> set password for ‘’@hostname = password(‘magicword’);
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit
Bye
The semicolons (;) terminating each command are required The first mand starts the MySQL shell, a command interpreter for the MySQL databaseserver, using MySQL’s root account The rest of the commands are executedfrom the MySQL shell, which uses the mysql> prompt In your commands,replace magicword with the password you’ve chosen and hostname with
Trang 5com-the fully qualified domain name of your system The flush privilegesinstruction causes MySQL to reread the access tables and makes the new pass-word for the anonymous account take effect Notice that the anonymous user-name is specified using a pair of single quotes This is necessary because theanonymous account doesn’t, strictly speaking, have a username The last com-mand, quit, terminates the MySQL shell session and returns you to the com-mand prompt.
T I P If you make a real mess of the instructions in this section or just want to start over, you can restore your MySQL installation to its original state by using the following procedure:
1 Stop MySQL:
# service mysqld stop
2 Delete the MySQL data directories and files in /var/lib/mysql:
# cd /var/lib/mysql
# rm -rf mysql test
3 Restart MySQL:
# service mysqld start
This procedure works because the mysqld initialization script creates the initial databases if the directory /var/lib/mysql/mysql doesn’t exist.
If you prefer to delete the anonymous accounts entirely, use the followingcommands:
$ mysql -u root -p
Enter password:
mysql> delete from mysql.user where user = ‘’;
Query OK, 2 rows affected (0.02 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec);
mysql> quit
Bye
With the root account properly secured and having made a decision abouthow to handle the anonymous accounts, you are ready to learn a bit moreabout the MySQL client programs
Trang 6Using the MySQL Client Programs
What precisely is a MySQL client program? MySQL is a standard client-serverprogram The MySQL server daemon, mysqld, is the actual database server Itlistens for incoming connections and retrieves, manipulates, and returns data
It has no interface other than that provided by a client API Programs that arewritten to MySQL’s client API provide the user interface to the MySQL server
It is the client programs that enable you to submit queries to the database, toadd and delete users, and so on The client programs also make it easier to per-form certain tasks For example, in theory, a SQL database can be manipulatedentirely using SQL statements However, to simplify certain activities, it isoften more convenient to use programs that hide SQL functionality behind asimpler interface MySQL’s client programs provide this simpler interface
You’ve already seen three of the MySQL client programs in action,mysqladmin, mysqlshow, and mysql mysqladmin is a utility that enablesyou to perform administrative activities, such as:
■■ Creating, modifying, and deleting (dropping, in SQL parlance) databases
■■ Starting and stopping the MySQL server
■■ Confirming the database is up
■■ Finding out which server threads are running
■■ Killing specific MySQL server threads
■■ Retrieving status information from a running server
■■ Flushing (syncing) data to disk
■■ Changing passwordsmysqladmin’s basic syntax is:
mysqladmin -u username -p[password] command
Replace username with the database username, such as root, that you want
to use The account specified in username must have the privileges required
to perform the requested operation If you specify just -p, MySQL will promptyou for username’s password You can add the password after -p, but doing
so isn’t a good idea because it will appear on screen command specifies theoperation you want to perform For example, to create a database namedtechbooks, the command would be:
mysqladmin -u username -p create techbooks
To delete (drop) this database, use the following command:
Trang 7To change the password for the root user, you would use the following command:
mysqladmin -u username -p password ‘new_password’
Replace new_password with the password you want to assign to usernameand make sure to enclose the new password in single quotes (‘) In this case thecommand passed to mysqladmin is password ‘new_password’; the -p
option is not being given an argument of password.
To stop a running server, use the shutdown command, as shown in the lowing example:
fol-mysqladmin -u username -p shutdown
For more details about using the mysqladmin command, see themysqladminmain page or refer to the MySQL documentation
mysqlshowis a utility that displays the structure of a MySQL database, thetables in that database, and the columns (or fields) that make up that database
It uses an option syntax similar mysqladmin, but takes different (and fewer)arguments:
mysqlshow -u username -p [database [table [column]]]
As before, replace username with the user account you want to use Ifdatabaseis not specified, mysqlshow displays all of the available databases
If database is specified, mysqlshow lists the tables that exist in database Iftableis also specified (it must exist in the indicated database), mysqlshowdisplays that table’s columns (fields) If column is also specified (the columnmust exist in the specified table, which must likewise exist in the requesteddatabase), mysqlshow displays that column’s characteristics For example,the following command display the tables in the mysql database:
$ mysqlshow -u root -p mysql
Database: mysql + -+
| Tables | + -+
Trang 8mysql, as already explained, is a MySQL shell or command interpreter Thecommands it interprets are SQL statements mysql gives you the most directaccess to the MySQL’s database engine, but also requires that you speak fluentSQL You enter SQL statements at a command prompt, the interpreter passesthem to the database engine, and the database engine sends the results of thoseSQL statements back the interpreter, which displays the results on the screen.There are many other MySQL clients Table 15-1 lists the ones you are mostlikely to use; there are others, but they are special-purpose programs that (wehope) you never need to use.
We don’t have the space to go into all of MySQL’s capabilities, much lessprovide proper guidance on using all its commands and utilities The initialsetup instructions and the short introduction to some of the MySQL clientcommands should, nevertheless, get you started Fortunately, one of MySQL’sstrongest selling points is that it is ready to run with minimal setup after instal-lation and that it requires very little ongoing maintenance MySQL’s simplicitymakes it an ideal choice for busy system administrators who have enough to
do keeping their mail servers from getting clogged up with spam and viruseswithout having to learn how to maintain a complicated RDBMS As remarked
at the beginning of this section, MySQL is an extremely popular database withWeb programmers, precisely because it is easy to use and requires little in theway of ongoing care and feeding If, after some period of time, you outgrowMySQL, it might be time to consider PostgreSQL, discussed in the next section
Table 15-1 MySQL Client Programs
PROGRAM DESCRIPTION
mysql Provides an interactive command interpreter for the MySQL
server mysqlaccess Adds new users to MySQL mysqladmin Performs MySQL administrative functions mysqlbinlog Displays a MySQL binary log file in a format readable by humans mysqlbug Creates and files bug reports for MySQL
mysqlcheck Tests, repairs, analyzes, and optimizes MySQL databases mysqldump Backs up or restores data from or to a MySQL database mysqldumpslow Displays and summaries MySQL’s query log, producing
information you can use to optimize slow queries mysqlimport Imports data into MySQL tables from text files of various formats mysqlshow Displays the structure of MySQL databases, tables, and columns mysqltest Runs a database test and compares the results to previous runs
Trang 9Using PostgreSQL
PostgreSQL is the second most popular free RDBMS It provides some featuresnot available in MySQL, so if you find you need features or functionality thatMySQL lacks, PostgreSQL might be the solution you need As with MySQL,PostgreSQL is popular with Linux users because it is free; fast; feature-rich;easy to set up, use, and maintain; and provides fuller support for the ANSISQL99 and SQL 2003 standards than MySQL does Like MySQL, PostgreSQL
is also widely supported by and integrated into a variety of third-party cations There are numerous Apache modules that make it possible to usePostgreSQL in Apache-based Web servers, and PHP’s support for PostgreSQL
appli-is surpassed only by PHP’s support for MySQL Among scripting languages,Perl and Python have wide support for PostgreSQL, and PostgreSQL’s clientAPI makes it possible and reasonably easy to include PostgreSQL support in Cand C++ applications
Out of the box, PostgreSQL is ready to use You’ll need to make sure that it
is installed of course, and there are some postinstallation tasks you need toperform to secure the database and to make sure the database is functioningand answering requests This section will also show you, briefly, how to usesome of the PostgreSQL client commands
Why would you want to use PostgreSQL instead of MySQL? The easiestanswer is that you should use PostgreSQL if it has a feature or functionalitythat MySQL doesn’t If you are looking for standards compliance, PostgreSQL
is more compliant with SQL standards than MySQL is and supports certaintypes of SQL queries that MySQL doesn’t Traditionally, the biggest knock
against MySQL was that it was just a glorified data file (an ISAM or index sequential access method file, to be precise) that supported SQL-driven data
access PostgreSQL, on the other hand, while providing persistent data storageusing the file system, used to have a different in-memory layout to supportSQL-driven data access This distinction is no longer true because MySQL nowprovides multiple methods of persistent data storage and is no longer anISAM-based one-trick pony
PostgreSQL is more marketing-buzzword-compliant, too, in that it supportsspatial data types and is object-relational The spatial data types make it possi-
ble to create GIS applications using PostgreSQL Object-relational means that
PostgreSQL can use standard SQL access methods and relational data tures to access and manipulate object-oriented data To provide some guid-ance, we have prepared a sidebar, “MySQL or PostgreSQL,” that provides aside-by-side comparison of the two packages
struc-To return to the original question, which one should you use? We can’t tellyou As a system administrator, these concerns are ordinarily peripheral toyour primary job function You maintain the system on which the database
Trang 10runs and possibly install/upgrade the software and perform the initial
config-uration It is up to information architects and database administrators (DBAs)
to make decisions about which database to use and the relative merits of onedatabase or another Of course, not every site running Linux has the luxury ofthis kind of separation of duties The system administrator of smaller sites isoften also the DBA (and the network administrator, mail administrator, Web-master, telephone technician, and brewer of the morning coffee), so it pays to
be familiar with the broad outlines of database features
Table 15-2 Database Feature Comparison
FEATURE MYSQL POSTGRESQL
Complex queries (UNION, UNION ALL, EXCEPT) Yes Yes Cross-database compatibility features Yes Yes
(continued)
MYSQL OR POSTGRESQL?
If you want to start an argument among in a group of people familiar with free RDBMSes, ask them which is better, PostgreSQL or MySQL It is not this chapter’s intent to start an argument, so it avoids saying which is better There are
significant differences between MySQL and PostgreSQL, though, and knowing what these differences are might help you decide which one to use Table 15-2 lists features generally expected to exist in a RDBMS and shows whether MySQL
and PostgreSQL as shipped in Fedora Core and RHEL support them.
As you can see in the table, PostgreSQL supports a larger set of features common in the commercial RDBMS world than MySQL However, bigger isn’t necessarily better because the richer feature set might be overkill for your needs.
In addition, the versions of PostgreSQL and MySQL that ship in Fedora Core and Red Hat Enterprise Linux lag somewhat behind the current stable versions of those products At the time this book went to press, the versions of PostgreSQL and MySQL shipping with Fedora Core and RHEL were 7.4.7 and 3.23.58, respectively, while the latest and greatest released versions were 8.0 and 4.1.9 (MySQL 5.0 had just entered an alpha release state).
For a fuller comparison of the features set of particular version PostgreSQL and MySQL, see the comparison table maintained by MySQL at
http://dev.mysql.com/tech-resources/features.html.
Trang 11Table 15-2 (continued)
FEATURE MYSQL POSTGRESQL
Extensible, user-defined data types No Yes
Assuming that you’ve decided that PostgreSQL is the database to use, thenext two sections show you how to get the standard PostgreSQL installationworking and how to use some of PostgreSQL’s client utilities
Trang 12Verifying the PostgreSQL Installation
You won’t get very far in this section if PostgreSQL is not installed You can usethe following commands to see if the key PostgreSQL RPMs are installed:
data-to use against C and C++ programs that use the PostgreSQL API If these fourpackages aren’t installed, install them as described in Chapter 30
Other PostgreSQL packages that might also be installed or that you mightwant to install include:
■■ postgresql-contrib— Includes selected contributed modules andprograms not part of the standard PostgreSQL distribution
■■ postgresql-docs— Provides a rich documentation suite in bothsource (SGML) and rendered formats suitable for online viewing orprinting
■■ postgresql-jdbc— Installs a Java database connectivity (JDBC) driver necessary to connect to PostgreSQL using Java
■■ postgresql-odbc— Installs the Open Database Connectivity (ODBC)driver necessary to connect to PostgreSQL using ODBC
■■ postgresql-pl— Contains PostgreSQL-specific procedural languagesfor Perl, Tcl, and Python, enabling you to use these languages to manipu-late the server
■■ postgresql-python— Includes Python support, and the PL/Pythonprocedural language for using Python with PostgreSQL
Trang 13■■ postgresql-tcl— Provides Tcl (Tool command language, anembeddable scripting language) support, the PL/Tcl procedural lan-guage, and a PostgreSQL-enabled tclsh (a Tcl shell)
■■ postgresql-test— Contains a number of test suites for performingbenchmark and regression tests against the PostgreSQL server
In addition to the packages in the preceding list, other RPMs provide greSQL-related functionality that you likely won’t need To keep this sectionsimple, we will only refer to programs and utilities provided by the fourrequired packages
Post-Finalizing the PostgreSQL Installation
On a fresh PostgreSQL installation, no data structures have been created.Rather, the software has been installed, the postgres user and group havebeen created, and the data directory, /var/lib/pgsql/data, has been cre-ated The steps you need to take to finalize the installation are:
1 Initialize the installation
2 Modify access privileges
3 Create a test database
4 Validate connectivity to the test database
The following sections describe each step in this process in more detail
Initializing the Installation
Use the following procedure to initialize the installation, which consists of ating template data structures and starting the database server:
cre-1 Become the postgres user using su You do this in two steps, first
su-ing to the root account and then su-ing to the postgres useraccount:
Trang 14like -D /var/lib/pgsql/data to all of the PostgreSQL commandsyou use It gets tedious and is error-prone, so set the environment vari-able and forget about it.
3 Create the database cluster A database cluster refers to the data directory
and supporting files and directories stored therein, which serve as atemplate used to create the databases managed by a single PostgreSQLserver (yes, you can have multiple PostgreSQL servers, but we aren’tgoing to go there):
-bash-3.00$ initdb
The files belonging to this database system will be owned by user
“postgres”.
This user must also own the server process.
The database cluster will be initialized with locale en_US.UTF-8.
fixing permissions on existing directory /var/lib/pgsql/data ok creating directory /var/lib/pgsql/data/base ok
creating directory /var/lib/pgsql/data/global ok creating directory /var/lib/pgsql/data/pg_xlog ok creating directory /var/lib/pgsql/data/pg_clog ok selecting default max_connections 100
selecting default shared_buffers 1000 creating configuration files ok creating template1 database in /var/lib/pgsql/data/base/1 ok initializing pg_shadow ok
enabling unlimited row size for system tables ok initializing pg_depend ok
creating system views ok loading pg_description ok creating conversions ok setting privileges on built-in objects ok creating information schema ok
vacuuming database template1 ok copying template1 to template0 ok
Success You can now start the database server using:
/usr/bin/postmaster -D /var/lib/pgsql/data or
/usr/bin/pg_ctl -D /var/lib/pgsql/data -l logfile start
If you didn’t set the value of the environment variable $PGDATA as ommended in Step 2, you must add -D /var/lib/pgsql/data to theinitdb command line to specify the location of the database cluster
Trang 15rec-/var/lib/pgsql/datais the default, but you can use any directory.The initialization process ensures that only the postgres user (androot, of course) has any access whatsoever to the database cluster.
4 Exit the postgres su session because the root user must perform thenext step:
-bash-3.00$ exit
logout
5 Start the database server You can use the commands shown at the end
of Step 3, but it is easier to use the initialization script, postgresql,which performs the same steps and also executes some sanity checksbefore starting the server
# service postgresql start Starting postgresql service: [ OK ]
With the PostgreSQL server running, you’re ready to proceed to the nextpart of the process, tightening up access to the server
Modifying Access Privileges
After you have initialized the installation, you will likely want to modify thedefault authentication scheme The default authentication scheme is called
trust authentication because it permits all local users to access the server using
any PostgreSQL-recognized username (including the PostgreSQL superuseraccount) Moreover, this access can use either UNIX-domain sockets (also
known as Berkeley sockets) or TCP/IP We suggest making of the following
modifications to the default access policy:
■■ Permit local access using only UNIX-domain sockets
■■ Require local users to connect to the server using their system loginaccounts
■■ Require remote users (connecting via TCP/IP) to use SSL
■■ Use strong encryption for password checking
The file /var/lib/pgsql/data/pg_hba.conf controls client cation It contains records that have one of three formats The first formataddresses authentication of local clients, that is, clients accessing the serverfrom same machine on which the server is running (localhost) The local accessformat has the following general form:
authenti-local database user auth [option]