Getting Started With MySQL

- Installation

- RPM-based Linux
- Debian Linux
- Slackware Linux
- FreeBSD
- OpenBSD
- NetBSD
- SCO OpenServer
- Solaris
- Compiling From Source
- Starting the Database at Boot Time

- Creating a Database
- Accessing a Database
- Accessing a Database With SQL Relay
- MySQL Quirks

Installation

I've sucessfully installed MySQL on Linux, FreeBSD, NetBSD, OpenBSD, SCO OpenServer and Solaris.

FreeBSD, OpenBSD, NetBSD and most Linux distributions come with MySQL and give you the option of installing it when you install the rest of the system. If you want or need to install it afterward, follow the instructions below.

RPM-based Linux

To install MySQL on an RPM-based Linux distribution like RedHat, Mandrake or TurboLinux, acquire the mysql, mysql-server and mysql-devel RPMS from RPMFind or possibly from the CD's that came with your distribution and install them using rpm -i.

Debian Linux

If you have configured apt as illustrated in the APT-HOWTO, run apt-get install mysql-server and apt-get install libmysqlclientclient6-dev. If your distribution came with MySQL, you may be promted to enter a CD. If not, it will be downloaded from the internet. When the commands complete, MySQL will be installed. MySQL packages don't appear to be available for older Debian releases, so for those releases, I've always compiled it from source. Alternatively, you can download a binary distribution in tar.gz format from the MySQL site.

Slackware Linux

The mysql package is available from ftp.slackware.com. You can install it using installpkg.

FreeBSD

If you have an internet connection, run pkg_add -r mysql. When the command completes, MySQL will be installed. You can also install MySQL from the Ports CD(s) that came with your distribution using /stand/sysinstall.

OpenBSD

The mysql-client and mysql-server packages are available from ftp.openbsd.org or on CD's that came with your distribution. You can install them using pkg_add.

NetBSD

The mysql-client and mysql-server packages are available from ftp.netbsd.org or on CD's that came with your distribution. You can install them using pkg_add.

SCO OpenServer

For SCO OpenServer, MySQL packages are available from the Skunkware ftp server. SCO OpenServer packages are often called VOL's because they come as a set of files named VOL.000.000, VOL.000.001, etc. These VOLS can be installed using the Software Manager (custom).

Solaris

The Solaris Companion CD provides MySQL and its downloadable in package form from many web sites including the MySQL site. You can use pkgtool to install the package. Note, that with some versions of Solaris and some versions of MySQL, you have to create a "wheel" group before installing the MySQL package. You can do this (as root) using the command: /usr/sbin/groupadd wheel

Compiling From Source

If you want to compile MySQL from source, it should compile cleanly on all of the platforms mentioned above. The source code is available from the MySQL site. With older versions of MySQL, I've run out of memory while compiling on machines with less than 64 meg. I don't believe that this is still a problem though. I usually give the configure script the --prefix=/usr/local/mysql parameter so that MySQL will be installed entirely under /usr/local/mysql. I then add /usr/local/mysql/bin to my PATH environment variable and /usr/local/mysql/lib/mysql to my LD_LIBRARY_PATH environment variable.

Starting the Database at Boot Time

The package distributions of MySQL install a script which starts the database at boot time. If you compiled from source, you'll need to install a script like one of the following to start the database at boot time.

If you are using MySQL 4 or 5:

>     #!/bin/sh

>     case "$1" in
>             start)
>                     if ( test ! -d "/usr/local/mysql/var" ); then
>                             mkdir -p /usr/local/mysql/var/mysql
>                     fi
>                     if ( test ! -d "/usr/local/mysql/var/log" ); then
>                             mkdir -p /usr/local/mysql/var/log
>                     fi
>                     if ( test ! -d "/usr/local/mysql/var/mysql" ); then
>                             /usr/local/mysql/bin/mysql_install_db --datadir=/usr/local/mysql/var
>                     fi
>                     chown -R mysql.mysql /usr/local/mysql/var
>                     chmod 0755 /usr/local/mysql/var
>                     chmod 0755 /usr/local/mysql/var/log
>     		/usr/local/mysql/bin/mysqld_safe --datadir=/usr/local/mysql/var --err-log=/usr/local/mysql/var/log/mysqld.log --log=/usr/local/mysql/var/log/mysqld.log --socket=/tmp/mysql.sock
>                     ;;
>             stop)
>                     kill `ps -efa | grep mysql | grep -v grep | awk '{print $2}'`
>                     ;;
>             *)
>                     echo $"Usage: $0 {start|stop}"
>                     exit 1
>     esac

>     exit 0

If you are using MySQL 3:

>     #!/bin/sh

>     case "$1" in
>             start)
>                     if ( test ! -d "/usr/local/mysql/var/mysql" ); then
>                             /usr/local/mysql/bin/mysql_install_db
>                     fi
>                     chown -R mysql.mysql /usr/local/mysql/var
>                     chmod 0755 /usr/local/mysql/var
>                     /usr/local/mysql/bin/safe_mysqld
>                     ;;
>             stop)
>                     kill `ps -efa | grep mysql | grep -v grep | awk '{print $2}'`
>                     ;;
>             *)
>                     echo $"Usage: $0 {start|stop}"
>                     exit 1
>     esac

>     exit 0

Install this script and run it with the "start" option to start up the database. Running it with the "stop" option shuts the database down. To access a database, it must be running.

Creating a Database

After installation, MySQL is ready to use but to do any useful work, you'll have to create a database.

The installation process creates a database named mysql containing privileges and other housekeeping information and a root user which has no password.

The following commands give the root user the password newpassword.

> mysql -uroot -e "update user set password=password('newpassword') where user='root'" mysql
> mysqladmin -uroot reload

Though you can create tables in the mysql database, it's not a good idea. You should create a new database. The following command creates a database called testdb.

> mysqladmin -uroot -pnewpassword create testdb

To create a user, log into the mysql database using the following command.

> mysql -uroot -pnewpassword mysql

The following queries create a user called testuser with password testpassword and allows it to log in from the local machine or any remote host.

>     insert into user (host,user,password) values ('localhost','testuser',password('testpassword'));
>     insert into user (host,user,password) values ('%','testuser',password('testpassword'));

Once the user is created, it must be given database-specific priveleges. You'll need to run a query like the following to give testuser all privileges on the testdb database.

>     insert into db values ('%','testdb','testuser','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');

Various versions of MySQL have differnet numbers of columns in the db table, if the query above fails, run:.

>     desc db

Then count the number of columns with Type enum('N','Y') and re-run the query above using that number ,'Y' arguments.

Exit the mysql client and run the following command to activate these changes.

> mysqladmin -uroot -pnewpassword reload

To delete a user, log into the mysql database using the following command.

> mysql -uroot -pnewpassword mysql

Delete the appropriate rows from the user and db tables. The following queries remove the testuser user and all database-specific permissions that testuser had.

>     DELETE FROM user WHERE user='testuser';
>     DELETE FROM db WHERE user='testuser';

Exit the mysql client and run the following command to activate these changes.

> mysqladmin -uroot -pnewpassword reload

If you want to drop the database, you can do so with the following command.

> mysqladmin -uroot -pnewpassword drop testdb

This should be enough to get you started. To set up more complex configurations, consult the MySQL online documentation.

Accessing a Database

Accessing a MySQL database using the mysql client tool is simple. For example, to access a database called testdb on the local machine as the testuser user with password testpassword, use the following command.

> mysql -utestuser -ptestpassword testdb

If you want to access a database on a remote machine, say on testhost, use the -h option as follows.

> mysql -htesthost -utestuser -ptestpassword testdb

Once you're connected to the database, the mysql client prompts you to enter a query. Queries may be split across multiple lines. To run a query, end it with a semicolon or type \g on the next line. To exit, type \q.

A sample mysql session follows.

>     [user@localhost user]$ mysql -utestuser -ptestpassword testdb
>     Welcome to the MySQL monitor.  Commands end with ; or \g.
>     Your MySQL connection id is 5 to server version: 3.23.41

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

>     mysql> create table testtable (
>         -> col1 char(40),
>         -> col2 integer
>         -> );
>     Query OK, 0 rows affected (0.00 sec)

>     mysql> show tables;
>     +------------------+
>     | Tables_in_testdb |
>     +------------------+
>     | testtable        |
>     +------------------+
>     1 row in set (0.00 sec)

>     mysql> describe testtable;
>     +-------+----------+------+-----+---------+-------+
>     | Field | Type     | Null | Key | Default | Extra |
>     +-------+----------+------+-----+---------+-------+
>     | col1  | char(40) | YES  |     | NULL    |       |
>     | col2  | int(11)  | YES  |     | NULL    |       |
>     +-------+----------+------+-----+---------+-------+
>     2 rows in set (0.00 sec)

>     mysql> insert into testtable values ('hello',50);
>     Query OK, 1 row affected (0.00 sec)

>     mysql> insert into testtable values ('hi',60);
>     Query OK, 1 row affected (0.00 sec)

>     mysql> insert into testtable values ('bye',70);
>     Query OK, 1 row affected (0.00 sec)

>     mysql> select * from testtable;
>     +-------+------+
>     | col1  | col2 |
>     +-------+------+
>     | hello |   50 |
>     | hi    |   60 |
>     | bye   |   70 |
>     +-------+------+
>     3 rows in set (0.00 sec)

>     mysql> update testtable set col2=0 where col1='hi';
>     Query OK, 1 row affected (0.00 sec)
>     Rows matched: 1  Changed: 1  Warnings: 0

>     mysql> select * from testtable;
>     +-------+------+
>     | col1  | col2 |
>     +-------+------+
>     | hello |   50 |
>     | hi    |    0 |
>     | bye   |   70 |
>     +-------+------+
>     3 rows in set (0.00 sec)

>     mysql> delete from testtable where col2=50;
>     Query OK, 1 row affected (0.00 sec)

>     mysql> select * from testtable;
>     +------+------+
>     | col1 | col2 |
>     +------+------+
>     | hi   |    0 |
>     | bye  |   70 |
>     +------+------+
>     2 rows in set (0.00 sec)

>     mysql> drop table testtable;
>     Query OK, 0 rows affected (0.00 sec)

>     mysql> \q
>     Bye

Accessing a Database With SQL Relay

Accessing MySQL from SQL Relay requires an instance entry in your sqlrelay.conf file for the database that you want to access. Here is an example sqlrelay.conf which defines an SQL Relay instance called mysqltest. This instance connects to the testdb database on the local machine as the user testuser with password testpassword.

    <?xml version="1.0"?>
    <!DOCTYPE instances SYSTEM "sqlrelay.dtd">
    <instances>

            <instance id="mysqltest" port="9000" socket="/tmp/mysqltest.socket" dbase="mysql" connections="3" maxconnections="5" maxqueuelength="0" growby="1" ttl="60" endofsession="commit" sessiontimeout="600" runasuser="nobody" runasgroup="nobody" cursors="5" authtier="listener" handoff="pass">
                    <users>
                            <user user="mysqltest" password="mysqltest"/>
                    </users>
                    <connections>
                            <connection connectionid="mysqltest" string="user=testuser;password=testpassword;db=testdb" metric="1"/>
                    </connections>
            </instance>

    </instances>

If you want to connect to a database on a remote machine, say on testhost, you would need to add host=testhost; to the string attribute of the connection tag.

Now you can start up this instance with the following command.

> sqlr-start -id mysqltest

To connect to the instance and run queries, use the following command.

> sqlrsh -id mysqltest

The following command shuts down the SQL Relay instance.

> sqlr-stop mysqltest

MySQL Quirks

Most versions of MySQL don't support transactions, but some do. If you're using MySQL-max or if you built MySQL with Innodb support, then you have the option of running MySQL with support for transactions.

MySQL does not support foreign key constraints. For example, take the following table declarations:

>     create table cars (
>             car_id  int     not null,
>             ...
>     );

>     create table carkeys (
>             carkey_id  int     not null,
>             ...
>     );

>     create table keys_of_cars (
>             car_id  int     not null,
>             carkey_id  int     not null,
>             ...
>             foreign key (car_id) references cars (car_id),
>             foreign key (carkey_id) references carkeys (carkey_id)
>     );

In many other databases, attempting to insert car_id's and carkey_id's into the keys_of_cars table will fail unless those car_id's and carkey_id's exist in the cars and carkeys tables respectively. Under MySQL, this will not fail.

What's quirky about MySQL is that it allows the foreign key syntax, but ignores it. Other databases that don't support foreign keys don't allow the syntax either.