Transferring data between databases and DBMSs

For many databases-particularly those in which legacy data is being redeployed into a DBMS-most of the data insertion occurs as the database is created. A common approach is to create a script that contains SQL statements that can be repeatedly replayed; it's the approach we used to create the winestore database. This has the advantage that the script can be run on many different DBMSs, and it makes migration easier than with the LOAD DATA INFILE approach.

To remove and partially rebuild the winestore database, we might author a script containing the statements shown in Example 3-3.

Example 3-3. Script for creating and inserting winestore data
DROP DATABASE winestore;
use winestore
CREATE TABLE customer (
  cust_id int(5) NOT NULL auto_increment,
  surname varchar(50) NOT NULL,
  firstname varchar(50) NOT NULL,
  initial char(1),
  title varchar(10),
  addressline1 varchar(50) NOT NULL,
  addressline2 varchar(50),
  addressline3 varchar(50),
  city varchar(20) NOT NULL,
  state varchar(20),
  zipcode varchar(5),
  country varchar(20),
  phone varchar(15),
  fax varchar(15),
  email varchar(30) NOT NULL,
  birthdate date(  ),
  salary int(7),
  PRIMARY KEY (cust_id),
  KEY names (surname,firstname)
INSERT INTO customer VALUES (NULL,'Marzalla','Dimitria', 'F','Mrs','171 Titshall
Ccl','','','St Albans','WA', '7608','Australia','(618)63576028','', 'Dimitria@Lucaston.
INSERT INTO customer VALUES (NULL,'LaTrobe','Anthony', 'Y','Mr','125 Barneshaw
5','Australia','(618)73788578','(618)73786674', '','1952-03-10',54000);
INSERT INTO customer VALUES (NULL,'Fong','Nicholas','K','Mr','99 Kinsala Pl',
INSERT INTO customer VALUES (NULL,'Stribling','James','','Mr','6 Woodburne Pl','','',
'Legana','QLD','6377','Australia','(617)66603522', '','', '1943-11-

The script in Example 3-3, which has been saved to a file winestore.database, can be replayed using the MySQL command and a shell redirection:

% mysql -ppassword < winestore.database

This script runs the command interpreter with the statements and commands listed in the file winestore.database.

Data that is already managed in a MySQL database can be extracted using the utility mysqldump:

% mysqldump -ppassword winestore > winestore.database

The statements to DROP, CREATE, and use the database can be manually added with an editor to permit replaying of the script. We manually added the first three lines of Example 3-3 after using mysqldump to create the script.

To use the script to create a duplicate database, winestore2, for testing, you can change the first three lines of Example 3-3 to:

DROP DATABASE winestore2;
use winestore2