By Paul DuBois
Cover | Table of Contents | Colophon
GRANT statement to set up the MySQL user
account. Then use that account's name and password
to make connections to the server.
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. Text that you type is shown in bold; non-bold text is program
output:
% mysql -h localhost -p -u root Enter password: ****** mysql> GRANT ALL ON cookbook.* TO 'cbuser'@'localhost' IDENTIFIED BY 'cbpass'; Query OK, 0 rows affected (0.09 sec) mysql> QUIT Bye
root
password where you see the ******. (If the MySQL
root user has no password, just press Return at
the password prompt.) Then issue a GRANT statement
like the one shown.
cookbook,
substitute its name where you see cookbook in the
GRANT statement. Note that you need to grant
privileges for the database even if the user account already exists.
However, in that case, you'll likely want to omit
the IDENTIFIED BY
'cbpass' part of the statement, because otherwise
you'll change that account's
current password.
'cbuser'@'localhost'
indicates the host from which
you'll be connecting to the MySQL server to access
the CREATE DATABASE statement
to create a database, a
CREATE TABLE statement
for each table you want to use, and
INSERT to add records to the tables.
GRANT statement used in the previous section
defines privileges for the cookbook database, but
does not create it. You need to create the database explicitly before
you can use it. This section shows how to do that, and also how to
create a table and load it with some sample data that can be used for
examples in the following sections.
cbuser account has been set up, verify
that you can use it to connect to the MySQL server. Once
you've connected successfully, create the database.
From the host that was named in the GRANT
statement, run the following commands to do this (the host named
after -h should be the host where the MySQL server
is running):
% mysql -h localhost -p -u cbuser Enter password: cbpass mysql> CREATE DATABASE cookbook; Query OK, 1 row affected (0.08 sec)
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('armchair',4,2); mysql> INSERT INTO limbs (thing,legs,arms) VALUES('phonograph',0,1); 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);
QUIT
statement.
mysql> prompt that indicates the program
is ready to accept queries. To illustrate, here's
what the welcome message looks like (to save space, I
won't show it in any further examples):
% mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 18427 to server version: 3.23.51-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
% mysql -h localhost -p -u cbuser Enter password: cbpass
|
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
|
% mysql -p
Enter password: DIR command in a DOS window to see full
names.
# general client program connection options [client] host=localhost user=cbuser password=cbpass # options specific to the mysql program [mysql] no-auto-rehash # specify pager for interactive mode pager=/usr/bin/less
[client]
group and a [mysql] group. Within a group, option
lines are written in name=value format,
where name corresponds to an option name
(without leading dashes) and value is the
option's value. If an option
doesn't take any value (such as for the
no-auto-rehash option), the name is listed by
itself with no trailing =value part.
localhost), you
don't need any host line. If your
MySQL username is the same as your operating system login name, you
can omit the % chmod 600 .my.cnf
root user, specify the user and password
options on the command line to override the option file values:
% mysql -p -u root
% mysql -p
Enter password: ← press Return herePATH setting. Then you'll be able
to run mysql from any directory easily.
% mysql
mysql: Command not found.
C:\> mysql
Bad command or invalid filename
% /usr/local/mysql/bin/mysql
C:\> C:\mysql\bin\mysql
PATH environment variable that
lists pathnames of directories where the shell looks for commands.
(See Recipe 1.9.) Then you can invoke
mysql from any directory by entering just its
name, and your shell will be able to find it. This eliminates a lot
of unnecessary pathname typing. An additional benefit is that because
you can easily run mysql from anywhere, you will
have no need to put your datafiles in the same directory where
mysql is located. When you're not
operating under the burden of running mysql from a
particular location, you'll be free to organize your
files in a way that makes sense to you, not in a way imposed by some
artificial necessity. For example, you can create a directory under
your home directory for each database you have and put the files
associated with each database in the appropriate directory.
PATH setting.
PATH to determine
which directories to look in for programs such as
mysql. Other variables are used by other programs
(such as PERL5LIB, which tells Perl where to look
for library files used by Perl scripts).
|
Shell
|
Possible startup files
|
|---|---|
|
csh, tcsh
|
.login, .cshrc,
.tcshrc
|
|
sh, bash,
ksh
|
.profile .bash_profile,
.bash_login, .bashrc
|
|
DOS prompt
|
C:\AUTOEXEC.BAT
|
PATH
variable so that it includes the directory where the
mysql program is installed. The examples assume
there is an existing PATH setting in one of your
startup files. If you have no PATH setting
currently, simply add the appropriate line or lines to one of the
files.
PATH. The instructions are
similar because you use the same syntax.
PATH variable lists the pathnames for one or
more directories. If an environment variable's value
consists of multiple pathnames, it's conventional
under Unix to separate them using the colon character
(:). Under Windows, pathnames may contain colons,
so the separator is the semicolon character ( ;).
PATH, use the instructions
that pertain to your shell:
mysql> prompt, type it
in, add a semicolon ( ;) at the end
to signify the end of the statement, and press Return. An explicit
statement terminator is
necessary; mysql doesn't
interpret Return as a terminator because it's
allowable to enter a statement using multiple input lines. The
semicolon is the most common terminator, but you can also use
\g
("go") as a synonym for the
semicolon. Thus, the following examples are equivalent ways of
issuing the same query, even though they are entered differently and
terminated differently:
mysql> SELECT NOW( ); +---------------------+ | NOW( ) | +---------------------+ | 2001-07-04 10:27:23 | +---------------------+ mysql> SELECT -> NOW( )\g +---------------------+ | NOW( ) | +---------------------+ | 2001-07-04 10:27:28 | +---------------------+
mysql> to
-> on the second
input line. mysql changes the prompt this way to
let you know that it's still waiting to see the
query terminator.
; character
nor the \g sequence that serve as query
terminators are part of the query itself. They're
conventions used by the mysql program, which
recognizes these terminators and strips them from the input before
sending the query to the MySQL server. It's
important to remember this when you write your own programs that send
queries to the server (as we'll begin to do in the
next chapter). In that context, you don't include
any terminator characters; the end of the query string itself
signifies the end of the query. In fact, adding a terminator may well
cause the query to fail with an error.
USE
statement from within mysql.
cookbook.limbs refers to the
limbs table in the cookbook
database.) As a convenience, MySQL also allows you to select a
default (current) database so that you can refer to its tables
without explicitly specifying the database name each time. You can
specify the database on the command line when you start
mysql:
% mysql cookbook
% mysql -h host -p -u user cookbook
USE statement:
mysql> USE cookbook;
Database changed
mysql> SELECT DATABASE( );
+------------+
| DATABASE( ) |
+------------+
| cookbook |
+------------+
DATABASE( ) is a function that returns the name of the
current database. If no database has been selected yet, the function
returns an empty string:
mysql> SELECT DATABASE( );
+------------+
| DATABASE( ) |
+------------+
| |
+------------+
STATUS command (and its synonym,
\s) also display the current
database name, in additional to several other pieces of information:
mysql> \s
--------------
Connection id: 5589
Current database: cookbook
Current user: cbuser@localhost
Current pager: stdout
Using outfile: ''
Server version: 3.23.51-log
Protocol version: 10
Connection: Localhost via UNIX socket
Client characterset: latin1
Server characterset: latin1
UNIX socket: /tmp/mysql.sock
Uptime: 9 days 39 min 43 sec
Threads: 4 Questions: 42265 Slow queries: 0 Opens: 82 Flush tables: 1
Open tables: 52 Queries per second avg: 0.054
--------------\c sequence.
\c and type Return. This will return you to the
mysql> prompt:
mysql> SELECT * -> FROM limbs -> ORDER BY\c mysql>
\c appears to do nothing (that is, the
mysql> prompt does not reappear), which leads
to the sense that you're
"trapped" in a query and
can't escape. If \c is
ineffective, the cause usually is that you began typing a quoted
string and haven't yet entered the matching end
quote that terminates the string. Let
mysql's prompt help you figure
out what to do here. If the prompt has changed from
mysql> to
">, That
means mysql is looking for a terminating double
quote. If the prompt is '> instead,
mysql is looking for a terminating single quote.
Type the appropriate matching quote to end the string, then enter
\c followed by Return and you should be okay.
|
Editing Key
|
Effect of Key
|
|---|---|
|
Up Arrow
|
Scroll up through statement history
|
|
Down Arrow
|
Scroll down through statement history
|
|
Left Arrow
|
Move left within line
|
|
Right Arrow
|
Move right within line
|
|
Ctrl-A
|
Move to beginning of line
|
|
Ctrl-E
|
Move to end of line
|
|
Backspace
|
Delete previous character
|
|
Ctrl-D
|
Delete character under cursor
|
INSERT
statements shown earlier in Recipe 1.3 to create
the limbs table, first enter the initial
INSERT statement. Then, to issue each successive
statement, press the Up Arrow key to recall the previous statement
with the cursor at the end, backspace back through the column values
to erase them, enter the new values, and press Return.
USE statement.
no-auto-rehash line in the
[mysql] group of your MySQL option file:
[mysql] no-auto-rehash
REHASH
or \#
command at the mysql> prompt.
SELECT statement to a variable, then refer to the
variable later in your mysql session. This
provides a way to save a result returned from one query, then refer
to it later in other queries. The syntax for assigning a value to a
SQL
variable within a SELECT query is
@var_name
:=
value, where
var_name is the variable name and
value is a value that
you're retrieving. The variable may be used in
subsequent queries wherever an expression is allowed, such as in a
WHERE clause or in an INSERT
statement.
customers table with a cust_id
column that identifies each customer, and an
orders table that also has a
cust_id column to indicate which customer each
order is associated with. If you have a customer name and you want to
delete the customer record as well as all the
customer's orders, you need to determine the proper
cust_id value for that customer, then delete
records from both the customers and
orders tables that match the ID. One way to do
this is to first save the ID value in a variable, then refer to the
variable in the DELETE statements:
mysql> SELECT @id := cust_id FROM customers WHERE cust_id='customer name'; mysql> DELETE FROM customers WHERE cust_id = @id; mysql> DELETE FROM orders WHERE cust_id = @id;
SELECT statement assigns a column
value to a variable, but variables also can be assigned values from
arbitrary expressions. The following statement determines the highest
sum of the arms and legs
columns in the limbs table and assigns it to the
@max_limbs variable:
mysql> SELECT @max_limbs := MAX(arms+legs) FROM limbs;
LAST_INSERT_ID( ) after creating a new record in a
table that has an AUTO_INCREMENT column:
SOURCE
command.
% mysql cookbook < filename
\g), just
as if you were entering them manually.
One difference between interactive
and batch modes is the default output style. For interactive mode,
the default is tabular (boxed) format. For batch mode, the default is
to delimit column values with tabs. However, you can select whichever
output style you want using the appropriate command-line options. See
the section on selecting tabular or tab-delimited format later in the
chapter (Recipe 1.22).
recipes source distribution (see Appendix A). You can feed these files to
mysql in batch mode to avoid typing queries
yourself. A common instance of this is that when an example shows a
CREATE TABLE statement that
describes what a particular table looks like, you'll
find a SQL batch file in the distribution that can be used to create
(and perhaps load data into) the table. For example, earlier in the
chapter, statements for creating and populating the
% mysql cookbook < limbs.sql
% cat limbs.sql | mysql cookbook
% mysqldump cookbook | mysql -h some.other.host.com cookbook
INSERT statements by hand. Instead, write a short
program that generates the statements and send its output to
mysql using a pipe:
% generate-test-data | mysql cookbook
limbs table, run this command:
% mysql -e "SELECT COUNT(*) FROM limbs" cookbook
+----------+
| COUNT(*) |
+----------+
| 12 |
+----------+
% mysql -e "SELECT COUNT(*) FROM limbs;SELECT NOW( )" cookbook
+----------+
| COUNT(*) |
+----------+
| 12 |
+----------+
+---------------------+
| NOW( ) |
+---------------------+
| 2001-07-04 10:42:22 |
+---------------------+
=program
tells mysql to use a specific program as your
pager:
% mysql --pager=/usr/bin/less
PAGER
environment variable:
% mysql --pager
PAGER variable isn't set,
you must either define it or use the first form of the command to
specify a pager program explicitly. To define
PAGER, use the instructions in Recipe 1.9 for setting environment variables.
\P and
\n. \P
without an argument enables paging using the program specified in
your PAGER variable. \P with an
argument enables paging using the argument as the name of the paging
program:
mysql> \P PAGER set to /bin/more mysql> \P /usr/bin/less PAGER set to /usr/bin/less mysql> \n PAGER set to stdout
mysql> SELECT * FROM limbs;
+--------------+------+------+
| thing | legs | arms |
+--------------+------+------+
| human | 2 | 2 |
| insect | 6 | 0 |
| squid | 0 | 10 |
| octopus | 0 | 8 |
| fish | 0 | 0 |
| centipede | 100 | 0 |
| table | 4 | 0 |
| armchair | 4 | 2 |
| phonograph | 0 | 1 |
| tripod | 3 | 0 |
| Peg Leg Pete | 1 | 2 |
| space alien | NULL | NULL |
+--------------+------+------+
12 rows in set (0.00 sec)
% echo "SELECT * FROM limbs" | mysql cookbook
thing legs arms
human 2 2
insect 6 0
squid 0 10
octopus 0 8
fish 0 0
centipede 100 0
table 4 0
armchair 4 2
phonograph 0 1
tripod 3 0
Peg Leg Pete 1 2
space alien NULL NULL
% mysql cookbook > outputfile
% mysql cookbook < inputfile > outputfile
% mysql -t cookbook < inputfile | lpr % mysql -t cookbook < inputfile | mail paul
:) rather than tabs. Under
Unix, you can convert tabs to arbitrary delimiters by using utilities
such as tr and
sed. For example, to change tabs
to colons, any of the following commands would work
(TAB indicates where you type a tab
character):
% mysql cookbook < inputfile | sed -e "s/TAB/:/g" > outputfile % mysql cookbook < inputfile | tr "TAB" ":" > outputfile % mysql cookbook < inputfile | tr "\011" ":" > outputfile
% mysql cookbook < inputfile \ | sed -e 's/"/""/g' -e 's/TAB/","/g' -e 's/^/"/' -e 's/$/"/' > outputfile
#! /usr/bin/perl -w
while (<>) # read next input line
{
s/"/""/g; # double any quotes within column values
s/\t/","/g; # put `","' between column values
s/^/"/; # add `"' before the first value
s/$/"/; # add `"' after the last value
print; # print the result
}
exit (0);% mysql -e "SELECT * FROM limbs WHERE legs=0" cookbook +------------+------+------+ | thing | legs | arms | +------------+------+------+ | squid | 0 | 10 | | octopus | 0 | 8 | | fish | 0 | 0 | | phonograph | 0 | 1 | +------------+------+------+ % mysql -H -e "SELECT * FROM limbs WHERE legs=0" cookbook <TABLE BORDER=1> <TR><TH>thing</TH><TH>legs</TH><TH>arms</TH></TR> <TR><TD>squid</TD><TD>0</TD><TD>10</TD></TR> <TR><TD>octopus</TD><TD>0</TD><TD>8</TD></TR> <TR><TD>fish</TD><TD>0</TD><TD>0</TD></TR> <TR><TD>phonograph</TD><TD>0</TD><TD>1</TD></TR> </TABLE>
INSERT or
UPDATE statements.
% mysql -e "SELECT * FROM limbs WHERE legs=0" cookbook +------------+------+------+ | thing | legs | arms | +------------+------+------+ | squid | 0 | 10 | | octopus | 0 | 8 | | fish | 0 | 0 | | phonograph | 0 | 1 | +------------+------+------+ % mysql -X -e "SELECT * FROM limbs WHERE legs=0" cookbook <?xml version="1.0"?> <resultset statement="SELECT * FROM limbs WHERE legs=0"> <row> <thing>squid</thing> <legs>0</legs> <arms>10</arms> </row> <row> <thing>octopus</thing> <legs>0</legs> <arms>8</arms> </row> <row> <thing>fish</thing> <legs>0</legs> <arms>0</arms> </row> <row> <thing>phonograph</thing> <legs>0</legs> <arms>1</arms> </row> </resultset>