Installing and Using MySQL

You will learn in this tutorial how to install the MySQL data base server and client in Linux 7.0 and above. There is another version to install MySQL in Windows. You will also see the basics of using SQL to create a data base, insert and update data, perform queries, and drop (delete) a data base. Most of the commands used in this tutorial are part of the standard SQL specifications, but you may use the MySQL specific commands if you wish. Another tutorial is available from the people who developed MySQL. You should consider MySQL as a serious contender in the DB arena, considering that Yahoo and NASA, among others, use it and both the client and server are free for UNIX/Linux. The client is free but the server requires license in Windows NT/2000.



Downloading

I suggest you download the new stable version of MySQL: MySQL-3.23. RedHat 7.0 and above, and other distributions include MySQL in their distribution, but I still think that you do better downloading directly from theMySQL site.

Standard binary RPMs:

The best way to install software in Linux is using RPMs if they are available from a reputable source. In the MySQL site link I provided above you will find the current RPMs. Download them in any order, but install them in the order below:

  1. Client shared libraries for i386 systems:     MySQL-shared-3.23.44-1.i386.rpm
  2. Client programs for i386 systems:    MySQL-client-3.23.44-1.i386.rpm
  3. Include files and libraries for development for i386 systems:     MySQL-devel-3.23.44-1.i386.rpm
  4. The server for i386 systems:     MySQL-3.23.44-1.i386.rpm

Install the rpm files using rpm -ivh for the first and rpm -Uvh for the others. If you get messages like the following (where xx is a number like 37):

file /usr/bin/mysql from install of MySQL-client-3.23.44-1 conflicts with file from package mysql-3.23.xx-1
file /usr/bin/mysqlbinlog from install of MySQL-client-3.23.44-1 conflicts with file from package mysql-3.23.xx-1
file /usr/bin/mysqldump from install of MySQL-client-3.23.44-1 conflicts with file from package mysql-3.23.xx-1
file /usr/bin/mysqlimport from install of MySQL-client-3.23.44-1 conflicts with file from package mysql-3.23.xx-1
file /usr/bin/mysqlshow from install of MySQL-client-3.23.44-1 conflicts with file from package mysql-3.23.xx-1

Use the following rpm syntax (exemplified for the client) to override the conflicts:

rpm -Uvh MySQL-client-3.23.44-1.i386.rpm --replacefiles

Installation

When installed the server will display:

Preparing...                ########################################### [100%]
   1:MySQL                  ########################################### [100%]
Preparing db table
Preparing host table
Preparing user table
Preparing func table
Preparing tables_priv table
Preparing columns_priv table
Installing all prepared tables
010422 17:31:25 /usr/sbin/mysqld: Shutdown Complete

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
This is done with:
/usr/bin/mysqladmin -u root -p password 'new-password'
See the manual for more instructions.
Please report any problems with the /usr/bin/mysqlbug script!

The latest information about MySQL is available on the web at http://www.mysql.com
Support MySQL by buying support/licenses at https://order.mysql.com

Starting mysqld daemon with databases from /var/lib/mysql

IGNORE THE MESSAGE TO CHANGE THE PASSWORD: DO NOT CHANGE PASSWORD NOW

Note: If you try to change the password at this point in time it will not work. But, if you did it anyway and now you cannot login as root (access denied) you need to uninstall MySQL server:

rpm -e MySQL-3.23.37-1

and go in /var/lib and delete the subdirectory mysql. To be in the safe side reboot. Once you re-start, install the server again and do NOT change the password at this time.

Everything is installed and you should now start an interactive session with MySQL as follows:

Your first login

When the MySQL server is installed it does not have a password for the root user, so you can log typing at a shell prompt: mysql -u root mysql (you are asking to connect as user root and use the data base mysql, the basic DB installed by the server). You are placed at the mysql> prompt. The first thing you should do is to change the password like we did in the example below:

[root@alaptop /root]# mysql -u root mysql

Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 3.23.37

Type 'help;' or '\h' for help. Type '\c' to clear the buffer

mysql> set password for root=Password('pwserver');
Query OK, 0 rows affected (0.52 sec)

mysql> quit
Bye

Once I changed the password I quit to test the new password. I logged in with the new password as shown below:

[root@alaptop /root]# mysql -u root -p
Enter password:

Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 3.23.37

Type 'help;' or '\h' for help. Type '\c' to clear the buffer
mysql>

The new password worked and now you can issue commands. This is the end of the installation.




Server Administration

When you just type mysqladmin (see below) you obtain a list of all commands available for server administration through this command.

[root@alaptop /root]# mysqladmin  

Administration program for the mysqld daemon. Usage: mysqladmin [OPTIONS] command command....

  -#, --debug=...       Output debug log. Often this is 'd:t:o,filename`
  -f, --force           Don't ask for confirmation on drop database; with
                        multiple commands, continue even if an error occurs
  -?, --help            Display this help and exit
  --character-sets-dir=...
                        Set the character set directory
  -C, --compress        Use compression in server/client protocol
  -h, --host=#          Connect to host
  -p, --password[=...]  Password to use when connecting to server
                        If password is not given it's asked from the tty
  -P  --port=...        Port number to use for connection
  -i, --sleep=sec       Execute commands again and again with a sleep between
  -r, --relative        Show difference between current and previous values
                        when used with -i. Currently works only with
                        extended-status
  -E, --vertical        Print output vertically. Is similar to --relative,
                        but prints output vertically.
  -s, --silent          Silently exit if one can't connect to server
  -S, --socket=...      Socket file to use for connection
  -u, --user=#          User for login if not current user
  -v, --verbose         Write more information
  -V, --version         Output version information and exit
  -w, --wait[=retries]  Wait and retry if connection is down

Default options are read from the following files in the given order:
/etc/my.cnf /var/lib/mysql/my.cnf ~/.my.cnf
The following groups are read: mysqladmin client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit
--no-defaults           Don't read default options from any options file
--defaults-file=#       Only read default options from the given file #
--defaults-extra-file=# Read this file after the global files are read

Possible variables for option --set-variable (-O) are:
connect_timeout       current value: 0
shutdown_timeout      current value: 3600

Where command is a one or more of: (Commands may be shortened)
  create databasename   Create a new database
  drop databasename     Delete a database and all its tables
  extended-status       Gives an extended status message from the server
  flush-hosts           Flush all cached hosts
  flush-logs            Flush all logs
  flush-status          Clear status variables
  flush-tables          Flush all tables
  flush-threads         Flush the thread cache
  flush-privileges      Reload grant tables (same as reload)
  kill id,id,...        Kill mysql threads
  password new-password Change old password to new-password
  ping                  Check if mysqld is alive
  processlist           Show list of active threads in server
  reload                Reload grant tables
  refresh               Flush all tables and close and open logfiles
  shutdown              Take server down
  status                Gives a short status message from the server
  start-slave           Start slave
  stop-slave            Stop slave
  variables             Prints variables available
  version               Get version info from server
  
You can run any one of them by typing mysqladmin -p command name. You will be asked for the MySQL root password, and once you type it in, the command will execute.

Stop and start the MySQL server

Creating and droping data bases

Display existing data bases


mysql> show databases;
+----------+
| Database |
+----------+
| MYTEST   |
| mysql    |
| test     |
+----------+
3 rows in set (0.06 sec)
Please note that our recently created MYTEST database is listed.

Adding users

See URL http://www.mysql.com/doc/A/d/Adding_users.html for more details. The example below creates a new user abento, which can only login from the localhost (to make it to be from any host it would have been written abento@'%' instead of abento@localhost), with the password equal to pwserver (MySQL encrypts this password using a different algorithm than UNIX).

The abento user was GRANTED select,insert,update,delete,create and drop permissions on all data bases (*.*). If we had a table people in the MYTEST data base, and we only wanted abento to have rights in the table people, we would have written: ON MYTEST.people. We tested if the user had been added by loging as the new user abento, and typing a command to see the existing data bases (to test if the permissions were granted).


mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP ON *.* TO abento@localhost IDENTIFIED BY 'pwserver';
Query OK, 0 rows affected (1.39 sec)
 
mysql> quit
Bye
[root@alaptop /root]# mysql -u abento -ppwserver
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 26 to server version: 3.23.37
 
Type 'help;' or '\h' for help. Type '\c' to clear the buffer
 
mysql> show databases;
+----------+
| Database |
+----------+
| MYTEST   |
| mysql    |
| test     |
+----------+
3 rows in set (0.67 sec)

Others

[root@alaptop /root]# mysqladmin -p version
Enter password:
mysqladmin  Ver 8.19 Distrib 3.23.37, for pc-linux-gnu on i686
Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL license
 
Server version          3.23.37
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 39 min 32 sec
 
Threads: 1  Questions: 22  Slow queries: 0  Opens: 12  Flush tables: 1  Open tables: 6 Queries per second avg: 0.009
[root@alaptop /root]# mysqladmin -p status
Enter password:
Uptime: 2592  Threads: 1  Questions: 23  Slow queries: 0  Opens: 12  Flush tables: 1  Open tables: 6 Queries per second avg: 0.009
To see all threads and processes running use:


[root@alaptop /root]# mysqladmin -p processlist
Enter password:
+----+------+-----------+----+---------+------+-------+------------------+
| Id | User | Host      | db | Command | Time | State | Info             |
+----+------+-----------+----+---------+------+-------+------------------+
| 8  | root | localhost |    | Query   | 0    |       | show processlist |
+----+------+-----------+----+---------+------+-------+------------------+
You can explicitly include the password in your login as shown below:


[root@alaptop /root]# mysql -u root -ppwserver
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9 to server version: 3.23.37
 
Type 'help;' or '\h' for help. Type '\c' to clear the buffer
But this is a security risk. You may use the explicit password value in a script, which you keep in a secure directory, but avoid using it at the shell prompt.




Creating and manipulating tables

Using MySQL to create and manipulate tables. See http://www.mysql.com/doc/R/e/Reference.html for more details.

If you recall, in a prior example a user abento was created as follows:


mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP ON *.* TO abento@localhost IDENTIFIED BY 'pwserver';
Query OK, 0 rows affected (1.39 sec)
Lets see the user abento login, use the MYTEST data base (created previously by root), create a table, and ask for the display of the table structure:


[root@alaptop /root]# mysql -u abento -ppwserver
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 29 to server version: 3.23.37

Type 'help;' or '\h' for help. Type '\c' to clear the buffer

mysql> \u MYTEST
Database changed

mysql> CREATE TABLE people (userid INT NOT NULL PRIMARY KEY, name CHAR(25), address CHAR(45));
Query OK, 0 rows affected (0.68 sec)

mysql> desc people;
+---------+----------+------+-----+---------+-------+
| Field   | Type     | Null | Key | Default | Extra |
+---------+----------+------+-----+---------+-------+
| userid  | int(11)  |      | PRI | 0       |       |
| name    | char(25) | YES  |     | NULL    |       |
| address | char(45) | YES  |     | NULL    |       |
+---------+----------+------+-----+---------+-------+
3 rows in set (0.09 sec)
Let us see the user abento try to change the definition of the table he created and fail. Why? Then root logs in and do the change. Why it worked now?

mysql> ALTER TABLE people MODIFY address VARCHAR(100);
ERROR 1044: Access denied for user: 'abento@localhost' to database 'MYTEST'

mysql> quit
Bye

[root@alaptop /root]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 30 to server version: 3.23.37
 
Type 'help;' or '\h' for help. Type '\c' to clear the buffer
 
mysql> use MYTEST
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
 
Database changed
mysql> ALTER TABLE people MODIFY address VARCHAR(100);
Query OK, 0 rows affected (0.12 sec)
Records: 0  Duplicates: 0  Warnings: 0
 
mysql> desc people;

+---------+--------------+------+-----+---------+-------+
| Field   | Type         | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+-------+
| userid  | int(11)      |      | PRI | 0       |       |
| name    | varchar(25)  | YES  |     | NULL    |       |
| address | varchar(100) | YES  |     | NULL    |       |
+---------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
 
mysql>
Of course, the secret was that the user abento was not granted permission to ALTER the table. So although it seemed that the user abento could do whatever he needed with the table, this was not the case. Be very careful how you grant permissions in data bases.

Inserting data into the tables

Once we create table structures (design, define the table) we are ready to add data to the tables. Lets see an example in MySQL

mysql> INSERT INTO people (userid,name,address) VALUES (347,'John Morris','1420 N. Charles St, Baltimore, MD 21201');
Query OK, 1 row affected (0.82 sec)

mysql> INSERT INTO people
 VALUES (458,'Al Bento','1420 N. Charles St, Baltimore, MD 21201');
Query OK, 1 row affected (0.00 sec)
 
mysql> INSERT INTO people VALUES (569,'Milt Jenkins','1420 N. Charles St, Baltimore, MD 21201');
Query OK, 1 row affected (0.00 sec)

Querying the table


mysql> SELECT * FROM people;
+--------+--------------+-----------------------------------------+
| userid | name         | address                                 |
+--------+--------------+-----------------------------------------+
|    347 | John Morris  | 1420 N. Charles St, Baltimore, MD 21201 |
|    458 | Al Bento     | 1420 N. Charles St, Baltimore, MD 21201 |
|    569 | Milt Jenkins | 1420 N. Charles St, Baltimore, MD 21201 |
+--------+--------------+-----------------------------------------+
3 rows in set (0.48 sec)
 
mysql>  SELECT * FROM people WHERE name = 'Al Bento';
+--------+----------+-----------------------------------------+
| userid | name     | address                                 |
+--------+----------+-----------------------------------------+
|    458 | Al Bento | 1420 N. Charles St, Baltimore, MD 21201 |
+--------+----------+-----------------------------------------+
1 row in set (0.51 sec)

mysql> SELECT userid,name FROM people WHERE address = '1420 N. Charles St, Baltimore, MD 21201';
+--------+--------------+
| userid | name         |
+--------+--------------+
|    347 | John Morris  |
|    458 | Al Bento     |
|    569 | Milt Jenkins |
+--------+--------------+
3 rows in set (0.00 sec)
 

Updating the tables

Updating is also very straightforward in MySQL:

mysql> UPDATE people SET name = 'Al Bento' WHERE userid = '347';
Query OK, 1 row affected (0.49 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM people WHERE name = 'Al Bento';
+--------+----------+-----------------------------------------+
| userid | name     | address                                 |
+--------+----------+-----------------------------------------+
|    347 | Al Bento | 1420 N. Charles St, Baltimore, MD 21201 |
|    458 | Al Bento | 1420 N. Charles St, Baltimore, MD 21201 |
+--------+----------+-----------------------------------------+
2 rows in set (0.00 sec)
 
 
mysql> UPDATE people SET name = 'John Morris' WHERE userid = '458';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0
 
mysql> SELECT * FROM people;
+--------+--------------+-----------------------------------------+
| userid | name         | address                                 |
+--------+--------------+-----------------------------------------+
|    347 | Al Bento     | 1420 N. Charles St, Baltimore, MD 21201 |
|    458 | John Morris  | 1420 N. Charles St, Baltimore, MD 21201 |
|    569 | Milt Jenkins | 1420 N. Charles St, Baltimore, MD 21201 |
+--------+--------------+-----------------------------------------+
3 rows in set (0.00 sec)

Looking into the user table of MySQL

Do not forget that all control tables of MySQL are MySQL tables! You can see their content and the permissions users were assigned, for example, when you read the table user.

mysql> use mysql
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

mysql> SELECT * FROM user;

+------------------+--------+------------------+-------------+-------------+-------------+--------------------+-----------+-------------+---------------+
| Host        | User      | Password         | Select_priv | Insert_priv | Update_priv | Delete_priv | Create_priv | Drop_priv | Reload_priv      | Shutdown_priv |
 Process_priv | File_priv | Grant_priv       | References_priv | Index_priv | Alter_priv |
+------------------+--------+------------------+-------------+-------------+-------------+--------------------+-----------+-------------+---------------+
| localhost   | root      | 1b50d85063ea8a6e | Y           | Y           | Y           | Y           | Y           | Y         | Y                | Y           |
  Y           | Y         | Y                | Y           | Y           | Y           |
| %           | abento    | 1b50d85063ea8a6e | Y           | Y           | Y           | Y           | N           | N         | N                | N           |
  N           | N         | N                | N           | N           | N           |
| localhost   | abento    | 1b50d85063ea8a6e | Y           | Y           | Y           | Y           | Y           | Y         | N                | N           |
  N           | N         | N                | N           | N           | N    |
+------------------+--------+------------------+-------------+-------------+-------------+--------------------+-----------+-------------+---------------+

6 rows in set (0.30 sec)


This page is maintained by Al Bento who can be reached at abento@ubmail.ubalt.edu. This page was last updated on April 21, 2001. Although we will attempt to keep this information accurate, we can not guarantee the accuracy of the information provided.