HomeMySQL Page 4 - Using Transactions In MySQL (Part 1)
Turning the Tables - MySQL
One of the most-requested MySQL features - transactions - is finally available in MySQL 4.0. In this first segment of a two-part article, learn about the theory behind the transactional model, find out how it can make your SQL applications more robust, and find out how to implement a transactional environment with MySQL's InnoDB table handler.
Now that you know the basics, let's take a little break from the theory and dive into the gritty reality of transactions. The first step is to create some InnoDB tables to use as a base for development. Before you can do this, though, you need to check if your MySQL build supports InnoDb tables. You can verify this by checking the "have_innodb" variable on a running MySQL server, as below:
mysql> SHOW VARIABLES LIKE 'have_innodb'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | have_innodb | YES | +---------------+-------+ 1 row in set (0.00 sec)
For BDB support, look for the "have_bdb" variable:
mysql> SHOW VARIABLES LIKE 'have_bdb'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | have_bdb | YES | +---------------+-------+ 1 row in set (0.00 sec)
Most recent MySQL binary distributions should support InnoDB out of the box. In case yours doesn't, or if you custom-built your MySQL server, you'll need to recompile it after adding the "--with-innodb" parameter to the configure script.
Now, even if InnoDB support is enabled, it doesn't mean that MySQL will create new tables using that format automatically. By default, when MySQL creates a new table, it does so using the MyISAM table format. As noted on the previous page, this table type does not support transactions. In order to tell MySQL to create an InnoDB table, therefore, it becomes necessary to add the optional TYPE clause to your CREATE TABLE command.
The following example illustrates, by creating an InnoDB table to store user names and passwords:
mysql> CREATE TABLE users ( -> id int(8) NOT NULL auto_increment, -> name varchar(255) NOT NULL default '', -> pass varchar(255) NOT NULL default '', -> PRIMARY KEY (id) -> ) TYPE=InnoDB; Query OK, 0 rows affected (0.16 sec)
In a similar manner, create two other tables, one for group memberships and the other for mailbox configuration.
mysql> CREATE TABLE groups ( -> uid int(8) NOT NULL default '0', -> grp varchar(255) NOT NULL default '' -> ) TYPE=InnoDB; Query OK, 0 rows affected (0.09 sec)
In case you already have MyISAM tables that you need to convert to InnoDB format for transactional usage, you might think that the only way is to manually back up the table data, drop the table, recreate it in InnoDB format and reinsert the records. You'd be wrong - MySQL allows you to alter the table type on the fly using the very cool ALTER TABLE command, as below: