My sql Study guide chapter 15

18

Click here to load reader

Transcript of My sql Study guide chapter 15

Page 1: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 1/18

MySQL® 5

CertificationStudy Guide

800 East 96th Street, Indianapolis, Indiana 46240 USA

Paul DuBois, Stefan Hinz, and Carsten Pedersen

Presented by:

Page 2: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 2/18

MySQL 5 Certification Study Guide

Copyright © 2006 by Pearson Education

 All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or

transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without  written permission from the publisher. No patent liability is assumed with respect to the use of the

information contained herein. Although every precaution has been taken in the preparation of this

book, the publisher and author assume no responsibility for errors or omissions. Nor is any liability 

assumed for damages resulting from the use of the information contained herein.

International Standard Book Number: 0-672-32812-7

Library of Congress Catalog Card Number: 2005902140

Printed in the United States of America

First Printing: August 2005

08 07 06 05 4 3 2 1

Trademarks

 All terms mentioned in this book that are known to be trademarks or service marks have been appropri-

ately capitalized. Pearson Education cannot attest to the accuracy of this information. Use of a term in

this book should not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer

Every effort has been made to make this book as complete and as accurate as possible, but no warranty 

or fitness is implied. The information provided is on an “as is” basis.

Bulk SalesPearson Education offers excellent discounts on this book when ordered in quantity for bulk purchases

or special sales. For more information, please contact 

U.S. Corporate and Government Sales

1-800-382-3419

[email protected] 

For sales outside of the U.S., please contact 

International Sales

[email protected] 

Page 3: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 3/18

15Importing and Exporting Data

This chapter discusses how to perform bulk data import and export operations. It covers

the following exam topics:

n Using the LOAD DATA INFILE statement to import data from filesn Using SELECT … INTO OUTFILE to export data to files

n Using mysqlimport and mysqldump for importing and exporting data from the command

line

15.1 Import and Export Operations MySQL includes two SQL statements that can be used to import data from files into your

database or export data from your database into files:

n LOAD DATA INFILE reads data records directly from a file and inserts them into a table.

n SELECT … INTO OUTFILE writes the result of a SELECT operation to a file.

 The two statements are related in the sense that they both transfer information between

 MySQL and data files. Also, both statements use similar syntax for describing the format of 

data file contents.

Data file import and export also can be performed from the command line. This is done

using the mysqlimport and mysqldump client programs. For bulk data transfer operations,

these programs act as command-line interfaces to the LOAD DATA INFILE and SELECT … INTO

OUTFILE statements. Each program examines its arguments to determine what you want it to

do, and then constructs appropriate SQL statements and sends them to the MySQL serveron your behalf.

Page 4: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 4/18

258 CHAPTER 15 Importing and Exporting Data

15.2 Importing and Exporting Using SQL This section discusses how to perform data import and export operations using SQL state-

ments. LOAD DATA INFILE reads the records from a data file and inserts them into a table.

SELECT … INTO OUTFILE writes the record in a result set to a file.

 The two statements are not quite opposites. LOAD DATA INFILE imports a file into a single

table, whereas SELECT … INTO OUTFILE can write a result set that may be produced by 

selecting from multiple tables.

15.2.1 Importing Data with LOAD DATA INFILELOAD DATA INFILE provides an alternative to INSERT for adding new records to a table. INSERT

specifies data values directly in the text of the statement. LOAD DATA INFILE reads the values

from a separate data file.

 The simplest form of the LOAD DATA INFILE statement specifies only the name of the data fileand the table into which to load the file:

LOAD DATA INFILE ‘file_name’ INTO TABLE table_name;

 The filename is given as a quoted string. On Windows, the pathname separator character is

‘\’, but MySQL treats the backslash as the escape character in strings. To deal with this

issue, write separators in Windows pathnames either as ‘/’ or as ‘\\’. To load a file named

C:\mydata\data.txt, specify the filename as shown in either of the following statements:

LOAD DATA INFILE ‘C:/mydata/data.txt’ INTO TABLE t;

LOAD DATA INFILE ‘C:\\mydata\\data.txt’ INTO TABLE t;

 MySQL assumes, unless told otherwise, that the file is located on the server host, that it has

the default file format (columns separated by tab characters and terminated by \n newline

characters), and that each input line contains a value for each column in the table. However,

LOAD DATA INFILE has clauses that give you control over each of those aspects of data-loading

operations and more:

n  Which table to load

n  The name and location of the data file

n  Whether to ignore lines at the beginning of the data file

n

 Which columns to loadn  Whether to skip or transform data values before loading them

n How to handle duplicate records

n  The format of the data file

 The syntax for LOAD DATA INFILE is as follows, where optional parts of the statement are indi-

cated by square brackets:

Page 5: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 5/18

25915.2 Importing and Exporting Using SQL

LOAD DATA [LOCAL] INFILE ‘file_name’

[IGNORE | REPLACE]

INTO TABLE table_name

format_specifiers

[IGNORE n LINES][(column_list )]

[SET (assignment_list )]

15.2.1.1 Specifying the Data File Location

LOAD DATA INFILE can read data files that are located on the server host or on the client host:

n By default, MySQL assumes that the file is located on the server host. The MySQL

server reads the file directly.

n If the statement begins with LOAD DATA LOCAL INFILE rather than with LOAD DATA INFILE,

the file is read from the client host on which the statement is issued. In other words,

LOCAL means local to the client host from which the statement is issued. In this case, the

client program reads the data file and sends its contents over the network to the server.

 The rules for interpreting the filename are somewhat different for the server host and the

client host. Without LOCAL in the LOAD DATA INFILE statement, MySQL looks for the data file

located on the server host and interprets the pathname as follows:

n If you refer to the file by its full pathname, the server looks for the file in that exact 

location.

n If you specify a relative name with a single component, the server looks for the file in

the database directory for the default database. (This isn’t necessarily the database that 

contains the table into which you’re loading the file.)

n If you specify a relative pathname with more than one component, the server interprets

the name relative to its data directory.

Suppose that the server’s data directory is /var/mysql/data, the database directory for the

test database is /var/mysql/data/test, and the file data.txt is located in that database

directory. Using the filename interpretation rules just given, it’s possible to refer to the

data.txt file three different ways in a LOAD DATA INFILE statement:

n  You can refer to the file by its full pathname:

LOAD DATA INFILE ‘/var/mysql/data/test/data.txt’ INTO TABLE t;

n If test is the default database, you can refer to a file in the database directory using just 

the final component of its pathname:

LOAD DATA INFILE ‘data.txt’ INTO TABLE t;

Page 6: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 6/18

260 CHAPTER 15 Importing and Exporting Data

n  You can refer to any file in or under the server’s data directory by its pathname relative

to that directory:

LOAD DATA INFILE ‘./test/data.txt’ INTO TABLE t;

If you use LOCAL to read a data file located locally on the client host, pathname interpretation

is simpler:

n If you refer to the file by its full pathname, the client program looks for the file in that 

exact location.

n If you specify a relative pathname, the client program looks for the file relative to its

current directory. Normally, this is the directory in which you invoked the program.

Suppose that a data file named data.txt is located in the /var/tmp directory on the client 

host and you invoke the mysql program while located in that directory. You can load the file

into a tablet

using either of these two statements:LOAD DATA LOCAL INFILE ‘/var/tmp/data.txt’ INTO TABLE t;

LOAD DATA LOCAL INFILE ‘data.txt’ INTO TABLE t;

 The first statement names the file using its full pathname. The second names the file rela-

tive to the current directory. If you invoke the mysql program in the /var directory instead,

 you can still load the file using the same full pathname. However, the relative pathname to

the file is different than when running the program in the /var/tmp directory:

LOAD DATA LOCAL INFILE ‘tmp/data.txt’ INTO TABLE t;

15.2.1.2 Skipping Data File Lines To ignore the initial part of the data file, use the IGNORE n LINES clause, where n is an integer

that indicates the number of input lines to skip. This clause commonly is used when a file

begins with a row of column names rather than data values. For example, to skip the first 

input line, a statement might be written like this:

LOAD DATA INFILE ‘/tmp/data.txt’ INTO TABLE t IGNORE 1 LINES;

15.2.1.3 Loading Specific Table Columns

By default, LOAD DATA INFILE assumes that data values in input lines are present in the same

order as the columns in the table. If the data file contains more columns than the table, MySQL ignores the excess data values. If the data file contains too few columns, each miss-

ing column is set to its default value in the table. (This is the same way MySQL handles

columns that aren’t named in an INSERT statement.)

If input lines don’t contain values for every table column, or the data values are not in the

same order as table columns, add a comma-separated list of column names within parenthe-

ses at the end of the LOAD DATA INFILE statement. This tells MySQL how columns in the

Page 7: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 7/18

26115.2 Importing and Exporting Using SQL

table correspond to successive columns in the data file. A list of columns is useful in

two ways:

n If the rows of the data file don’t contain a value for every column in the table, a column

list indicates which columns are present in the file. Suppose that a table namedsubscriber has the following structure:

mysql> DESCRIBE subscriber;

+---------+------------------+------+-----+---------+----------------+

| Field | Type | Null | Key | Default | Extra |

+---------+------------------+------+-----+---------+----------------+

| id | int(10) unsigned | NO | PRI | NULL | auto_increment |

| name | char(40) | NO | | | |

| address | char(40) | NO | | | |

+---------+------------------+------+-----+---------+----------------+

Here, id is an AUTO_INCREMENT column. If you have a file /tmp/people.txt containing

names and addresses and want MySQL to generate ID numbers automatically, load the

file like this:

LOAD DATA INFILE ‘/tmp/people.txt’ INTO TABLE subscriber (name,address);

For any table column that isn’t assigned a value from the data file, MySQL sets it to its

default value. MySQL thus sets the id column to the next sequence value for each input 

line.

n If the order of the columns in the data file doesn’t correspond to the order of the

columns in the table, a column list tells MySQL how to match up columns properly.

For example, if the lines in people.txt contain addresses and names rather than names

and addresses, the statement to load the file looks like this instead:

LOAD DATA INFILE ‘/tmp/people.txt’ INTO TABLE subscriber (address,name);

Each item in the column list can be a table column name, as just described, or a user vari-

able. Reasons for specifying user variables in the column list are discussed in Section

15.2.1.4, “Skipping or Transforming Column Values.”

15.2.1.4 Skipping or Transforming Column Values

It is possible to skip columns in the data file, or to transform data values read from the file

before inserting them into the table. These features are available by specifying user variables

in the column list and the optional SET clause.

 To assign an input data column to a user variable rather than to a table column, provide the

name of a user variable in the column list. If you assign the column to a user variable but do

nothing else with the variable, the effect is to ignore the column rather than to insert it into

the table. Or, by including a SET clause, you can use expressions that transform the value

before inserting it.

Page 8: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 8/18

262 CHAPTER 15 Importing and Exporting Data

Suppose that you have a file named /tmp/people2.txt that was exported from a table similar

to the subscriber table, and that it contains four columns for each subscriber: ID number,

first name, last name, and address. The file’s contents need to be transformed in two ways

for loading into the subscriber table. First, the ID values are not compatible with those in

the subscriber table and should be ignored. Second, the first name and last name should beconcatenated with a space between. These transformations can be achieved as follows:

LOAD DATA INFILE ‘/tmp/people2.txt’ INTO TABLE subscriber

(@skip,@first,@last,address)

SET name=CONCAT(@first,’ ‘,@last);

15.2.1.5 LOAD DATA INFILE and Duplicate Records

 When you add new records to a table with an INSERT or REPLACE statement, you can control

how to handle new records containing values that duplicate unique key values already pres-

ent in the table. You can allow an error to occur, ignore the new records, or replace the oldrecords with the new ones. LOAD DATA INFILE affords the same types of control over duplicate

records by means of two modifier keywords. However, its duplicate-handling behavior dif-

fers slightly depending on whether the data file is on the server host or the client host, so

 you must take the data file location into account.

 When loading a file that’s located on the server host, LOAD DATA INFILE handles records that 

contain duplicate unique keys as follows:

n By default, an input record that causes a duplicate-key violation results in an error and

the rest of the data file isn’t loaded. Records processed up to that point are loaded into

the table.

n If you specify the IGNORE keyword following the filename, new records that causeduplicate-key violations are ignored and no error occurs. LOAD DATA INFILE processes the

entire file, loads all records not containing duplicate keys, and discards the rest.

n If you specify the REPLACE keyword after the filename, new records that cause duplicate-

key violations replace any records already in the table that contain the duplicated key 

 values. LOAD DATA INFILE processes the entire file and loads all its records into the table.

IGNORE and REPLACE are mutually exclusive. You can specify one or the other, but not both.

For data files located on the client host, duplicate unique key handling is similar, except that 

the default is to ignore records that contain duplicate keys rather than to terminate with an

error. That is, the default is as though the IGNORE modifier is specified. The reason for this isthat the client/server protocol doesn’t allow transfer of the data file from the client host to

the server to be interrupted after it has started, so there’s no convenient way to abort the

operation in the middle.

Page 9: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 9/18

26315.2 Importing and Exporting Using SQL

15.2.1.6 Information Provided by LOAD DATA INFILE

 As LOAD DATA INFILE executes, it keeps track of the number of records processed and the

number of data conversions that occur. Then it returns to the client an information string in

the following format (the counts in each field will vary perLOAD DATA INFILE

operation):Records: 174 Deleted: 0 Skipped: 3 Warnings: 14

 The fields have the following meanings:

n Records indicates the number of input records read from the data file. This is not nec-

essarily the number of records added to the table.

n Deleted indicates the number of records in the table that were replaced by input 

records having the same unique key value as a key already present in the table. The

 value may be non-zero if you use the REPLACE keyword in the statement.

n Skipped indicates the number of data records that were ignored because they contained

a unique key value that duplicated a key already present in the table. The value may benon-zero if you use the IGNORE keyword in the statement.

n Warnings indicates the number of problems found in the input file. These can occur for

several reasons, such as missing data values or data conversion (for example, converting

an empty string to 0 for a numeric column). The warning count can be larger than the

number of input records because warnings can occur for each data value in a record. To

see what caused the warnings, issue a SHOW WARNINGS statement after loading the data

file.

15.2.1.7 Privileges Required for LOAD DATA INFILE

LOAD DATA INFILE requires that you have the INSERT privilege for the table into which you

 want to load data, as well as the DELETE privilege if you specify the REPLACE modifier. If the

file is located on the client host, you must have read access for the file, but no additional

 MySQL privileges are required. However, if the data file is located on the server host, the

server itself must have read access for the file. In addition, you must have the FILE privilege.

FILE is an administrative privilege, so it’s likely that to use LOAD DATA INFILE without LOCAL,

 you’ll need to connect to the server as an administrative user such as root.

15.2.1.8 Efficiency of LOAD DATA INFILE

It is more efficient to load data with LOAD DATA INFILE than by using INSERT statements. For a

data file that is located on the server host, the MySQL server reads the file directly, so the

data values need not cross the network from the client to the server. But even for a data file

located locally on the client host, LOAD DATA INFILE is more efficient than INSERT because

there’s less overhead for parsing data values and because the rows are loaded in a single

operation. Some of the efficiency of loading multiple rows at once can be obtained with

multiple-row INSERT syntax, but LOAD DATA INFILE still is more efficient.

Page 10: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 10/18

264 CHAPTER 15 Importing and Exporting Data

15.2.2 Exporting Data with SELECT … INTO OUTFILE A SELECT statement normally creates a result set that the server returns to the client. For

example, when you issue a SELECT using the mysql client, the server returns the result and

mysql writes it in tabular format when run interactively or in tab-delimited format when runin batch mode.

 A variation on SELECT syntax adds an INTO OUTFILE clause. This form of SELECT writes the

result set directly into a file and thus is the complement of LOAD DATA INFILE. To use SELECT

in this way, place the INTO OUTFILE clause before the FROM clause. For example, to write the

contents of the Country table into a file named Country.txt, issue this statement:

SELECT * INTO OUTFILE ‘Country.txt’ FROM Country;

 The name of the file indicates the location where you want to write it. MySQL interprets

the pathname using the same rules that apply to LOAD DATA INFILE for files located on the

server host. For example, given the statement just shown, the server writes the file into thedatabase directory of the default database.

Use of INTO OUTFILE changes the operation of the SELECT statement in several ways:

n  The output produced by a SELECT … INTO OUTFILE statement never leaves the server

host. Instead of sending the result over the network to the client, the server writes it to

a file on the server host. To prevent files from being overwritten, either accidentally or

maliciously, the server requires that the output file not already exist.

n  The statement causes the server to write a new file on the server host, so you must con-

nect to the server using an account that has the FILE privilege.

n

 The file is created with filesystem access permissions that make it owned by the MySQL server but world-readable.

n  The output file contains one line per row selected by the statement. By default, column

 values are delimited by tab characters and lines are terminated with newlines, but you

can control the output format by adding format specifiers after the filename, as

described in Section 15.2.3, “Data File Format Specifiers.”

 The location and manner in which SELECT … INTO OUTFILE creates the file has several

implications:

n If you want to access the file directly, you must have a login account on the server host 

or be otherwise able to access files on that host somehow. For some purposes, this limi-tation might not be a problem. For example, you don’t need to access the file yourself 

to reload it later with LOAD DATA INFILE because the MySQL server can read it for you.

n  The file is world-readable, so anyone who has filesystem access on the server host can

read it. You probably don’t want to use SELECT … INTO OUTFILE to create files that 

contain sensitive information, unless perhaps you’re the only person with access to

the machine.

Page 11: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 11/18

26515.2 Importing and Exporting Using SQL

n  The file is owned by the MySQL server, so you might not be able to remove it after

 you’re done with it. It might be necessary to coordinate with the server administrator to

arrange for removal of the file.

 Without the OUTFILE keyword, SELECT … INTO can be used to fetch a single row of data into variables. These can be user variables, stored routine variables, or local variables. See

Section 18.5.4.2, “Assigning Variable Values with SELECT … INTO.”

15.2.3 Data File Format SpecifiersLOAD DATA INFILE and SELECT … INTO OUTFILE assume a default data file format in which col-

umn values are separated by tab characters and records are terminated by newlines. If a data

file to be read by LOAD DATA INFILE has different column separators or line terminators, you

must indicate what the format is so that MySQL can read the file contents correctly.

Similarly, if you want SELECT … INTO OUTFILE to write a file with different separators or ter-

minators, you’ll need to indicate the format to use. It’s also possible to control data valuequoting and escaping behavior.

 The format specifiers supported by LOAD DATA INFILE and SELECT … INTO OUTFILE don’t 

enable you to characterize individual columns in the data file. For example, you cannot 

indicate that column 3 is numeric or that column 17 contains dates. Instead, you define the

general characteristics that apply to all column values: What characters separate column

 values in data rows, whether values are quoted, and whether there is an escape character that 

signifies special character sequences.

For LOAD DATA INFILE, format specifiers are listed after the table name. For SELECT … INTO

OUTFILE, they follow the output filename. The syntax for format specifiers is the same forboth statements and looks like this:

FIELDS

TERMINATED BY ‘string ’

ENCLOSED BY ‘char ’

ESCAPED BY ‘char ’

LINES TERMINATED BY ‘string ’

 The FIELDS clause defines the formatting of data values within a line. The LINES clause

defines the line-ending sequence. In other words, FIELDS indicates the structure of column

 values within records and LINES indicates where record boundaries occur.

 The TERMINATED BY, ENCLOSED BY, and ESCAPED BY parts of the FIELDS clause may be given in

any order. You need not specify all three parts. Defaults are used for any that are missing (or

if the FIELDS clause itself is missing) :

n Data values are assumed to be terminated by (that is, separated by) tab characters. To

indicate a different value, include a TERMINATED BY option.

n Data values are assumed to be unquoted. To indicate a quote character, include

an ENCLOSED BY option. For LOAD DATA INFILE, enclosing quotes are stripped from input 

Page 12: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 12/18

266 CHAPTER 15 Importing and Exporting Data

 values if they’re found. For SELECT … INTO OUTFILE, output values are written enclosed

 within quote characters.

 A variation on ENCLOSED BY is OPTIONALLY ENCLOSED BY. This is the same as ENCLOSED for

LOAD DATA INFILE, but different for SELECT … INTO OUTFILE: The presence of OPTIONALLY

causes output value quoting only for string columns, not for all columns.

n  The default escape character is backslash (‘\’). Any occurrence of this character within

a data value modifies interpretation of the character that follows it. To indicate a differ-

ent escape character, include an ESCAPED BY option. MySQL understands the following

special escape sequences:

Sequence Meaning

\N NULL value

\0 NUL (zero) byte

\bBackspace

\n Newline (linefeed)

\r Carriage return

\s Space

\t Tab

\’ Single quote

\” Double quote

\\ Backslash

 All these sequences except \N are understood whether they appear alone or within a

longer data value. \N is understood as NULL only when it appears alone.

 The default line terminator is the newline (linefeed) character. To indicate a line-ending

sequence explicitly, use a LINES clause. Common line terminators are newline, carriage

return, and carriage return/newline pairs. Specify them as follows:

LINES TERMINATED BY ‘\n’

LINES TERMINATED BY ‘\r’

LINES TERMINATED BY ‘\r\n’

Because newline is the default line terminator, it need be specified only if you want to make

the line-ending sequence explicit. Newline terminators are common on Unix systems and

carriage return/newline pairs are common on Windows. The ESCAPED BY option controls only the handling of values in the data file, not how you

 write the statement itself. If you want to specify a data file escape character of ‘@’, you’d

 write ESCAPED BY ‘@’. That doesn’t mean you then use ‘@’ to escape special characters else-

 where in the statement. For example, you’d still specify carriage return as the line termina-

tion character using LINES TERMINATED BY ‘\r’, not using LINES TERMINATED BY ‘@r’.

Page 13: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 13/18

26715.3 Importing and Exporting Data from the Command Line

Suppose that a file named /tmp/data.txt contains information in comma-separated values

(CSV) format, with values quoted by double quote characters and lines terminated by car-

riage returns. To import the file into a table t, use this LOAD DATA INFILE statement:

LOAD DATA INFILE ‘/tmp/data.txt’ INTO TABLE t

FIELDS TERMINATED BY ‘,’ ENCLOSED BY ‘“‘

LINES TERMINATED BY ‘\r’;

 To export information in that same format, use this SELECT … INTO OUTFILE statement:

SELECT * INTO OUTFILE ‘/tmp/data-out.txt’

FIELDS TERMINATED BY ‘,’ ENCLOSED BY ‘“‘

LINES TERMINATED BY ‘\r’

FROM t;

15.2.4 Importing and Exporting NULL Values A NULL value indicates the absence of a value or an unknown value, which is difficult to rep-

resent literally in a data file. For import and export purposes, MySQL uses the convention

of representing NULL values by \N:

n For LOAD DATA INFILE, a \N appearing unquoted by itself as a column value is interpreted

as NULL. MySQL users sometimes assume that an empty value in an input file will be

handled as a NULL value, but that isn’t true. MySQL converts an empty input value to 0,

an empty string, or a “zero” temporal value, depending on the type of the correspon-

ding table column.

n For SELECT … INTO OUTFILE, MySQL writes NULL values to the output file as \N.

15.3 Importing and Exporting Data from theCommand Line

 The mysqlimport and mysqldump client programs provide a command-line interface for

importing and exporting data. mysqlimport imports data files into tables. mysqldump exports

tables to data files.

15.3.1 Importing Data withmysqlimport

 The mysqlimport client program loads data files into tables. It provides a command-line

interface to the LOAD DATA INFILE statement. That is, mysqlimport examines the options given

on the command line. It then connects to the server and, for each input file named in the

command, issues a LOAD DATA INFILE statement that loads the file into the appropriate table.

Because mysqlimport works this way, to use it most effectively, you should be familiar with

the LOAD DATA INFILE statement, which is discussed in Section 15.2.1, “Importing Data with

Page 14: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 14/18

268 CHAPTER 15 Importing and Exporting Data

LOAD DATA INFILE.” This section describes mysqlimport invocation syntax and how its options

correspond to various clauses of the LOAD DATA INFILE statement.

Invoke mysqlimport from the command line as follows:

shell> mysqlimport options db_name input_file ...

db_name names the database containing the table to be loaded and input_file names the file

that contains the data to be loaded. You can name several input files following the database

name if you like.

mysqlimport uses each filename to determine the name of the corresponding table into

 which the file’s contents should be loaded. The program does this by stripping off any file-

name extension (the last period and anything following it) and using the result as the table

name. For example, mysqlimport treats a file named City.txt or City.dat as input to be

loaded into a table named City. After determining the table name corresponding to the file-

name, mysqlimport issues a LOAD DATA INFILE statement to load the file into the table.Each table to be loaded by mysqlimport must already exist, and each input file should con-

tain only data values. mysqlimport isn’t intended for processing dump files that consist of 

SQL statements. (Such files can be created with the mysqldump program; for instructions on

processing an SQL-format dump file, see Section 32.8.1, “Reloading mysqldump Output.”)

 The options part of the mysqlimport command may include any of the standard connection

parameter options, such as --host or --user. You’ll need to supply these options if the

default connection parameters aren’t appropriate. mysqlimport also understands options spe-

cific to its own operation. Invoke mysqlimport with the --help option to see a complete list 

of the options that can be used to tell mysqlimport the actions you want it to perform.

By default, input files for mysqlimport are assumed to contain lines terminated by newlines,

 with each line containing tab-separated data values. This is the same default format assumed

by the LOAD DATA INFILE statement. For an input file that’s in a different format, use the fol-

lowing options to tell mysqlimport how to interpret the file:

n --lines-terminated-by=string 

string specifies the character sequence that each input line ends with. The default is \n

(linefeed, also known as newline); other common line terminators are \r (carriage

return) and \r\n (carriage return/linefeed pairs).

n --fields-terminated-by=string 

string specifies the delimiter between data values within input lines. The default delimiter is \t (tab) .

n --fields-enclosed-by=char or --fields-optionally-enclosed-by=char 

char indicates a quote character that surrounds data values in the file. By default, values

are assumed to be unquoted. Use one of these options if values are quoted. A common

 value for char is the double quote character (‘“‘). If quote characters enclose a data

 value, they’re removed before the value is loaded into the table.

Page 15: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 15/18

26915.3 Importing and Exporting Data from the Command Line

n --fields-escaped-by=char 

By default, ‘\’ within the input is taken as an escape character that signifies a special

sequence. For example, if the \N sequence occurs alone in a field, it’s interpreted as a

NULL value. Use this option to specify a different escape character. To turn escaping off 

(no escape character), specify an empty value for char .

 The preceding options give you the flexibility to load input files containing data in a variety 

of formats. Some examples follow; each one loads an input file named City.txt into the City

table in the world database. Commands that are shown on multiple lines should be entered

on a single line.

 The following command loads a file that has lines ending in carriage return/linefeed pairs:

shell> mysqlimport --lines-terminated-by=”\r\n” world City.txt

Note that the --lines-terminated-by value is quoted with double quotes. Format option

 values often contain special characters, such as backslash, that might have special meaning to your command interpreter. It might be necessary to quote such characters to tell your com-

mand interpreter to pass them unchanged to mysqlimport.

 The syntax for specifying a double quote is trickier and depends on which command inter-

preter you use. The following command loads a data file containing values quoted by double

quote characters:

shell> mysqlimport --fields-enclosed-by=’”’ world City.txt

 This command should work on most Unix shells, which allow the double quote character to

be quoted within single quotes. This doesn’t work on Windows, where you must specify a

double quote within a double-quoted string by escaping it:

shell> mysqlimport --fields-enclosed-by=”\”” world City.txt

 The following command loads a file that has data values separated by commas and lines

ending with carriage returns:

shell> mysqlimport --fields-terminated-by=,

--lines-terminated-by=”\r” world City.txt

Other mysqlimport options provide additional control over data file loading. The following

list discusses some of those you’re likely to find useful:

n --ignore or --replace

 These options tell mysqlimport how to handle input records that contain unique key 

 values that are already present in the table. Such records result in duplicate-key errors

and cannot be loaded by default. --ignore causes duplicates in the input file to be

ignored. --replace causes existing records in the table to be replaced by duplicates in

the input file. These options correspond to the use of IGNORE or REPLACE with LOAD DATA

INFILE.

Page 16: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 16/18

270 CHAPTER 15 Importing and Exporting Data

n --local

By default, a data file to be loaded into a table is assumed to reside on the server host,

allowing the server to read the file directly. This is very efficient, but requires the user

running mysqlimport to have the FILE privilege (a powerful privilege normally reserved

for administrators). The --local option allows use of a data file that’s located locally on

the client host where mysqlimport is invoked. With --local, mysqlimport reads the data

file and sends it over the network to the server. This allows mysqlimport to read any file

on the client host to which the invoker has access, without requiring the invoker to

have the FILE privilege. For the --local option to work, the server must be configured

to allow local files to be transferred to it. This option corresponds to the use of  LOCAL

 with LOAD DATA INFILE.

15.3.2 Exporting Data with mysqldump

 The mysqldump client program dumps table contents to files. It is useful for making databasebackups or for transferring database contents to another server. mysqldump can export tables

as tab-delimited data files or produce SQL-format dump files that contain CREATE TABLE and

INSERT statements for re-creating the dumped files. This section discusses how to use

mysqldump to export tables as data files. For information on creating SQL-format dump files,

see Section 32.4.2, “Making Text Backups with mysqldump.”

 To use mysqldump to export tables as tab-delimited data files, specify the --tab=dir_name (or

-T dir_name) option on the command line. This option causes mysqldump to issue SELECT …

INTO OUTFILE statements to tell the MySQL server to write each dumped table as a tab-

delimited text file in the dir_name directory. For each table, mysqldump itself writes a file con-

taining a CREATE TABLE statement that you can use to re-create the table before reloading thedata file into it.

Invoke mysqldump from the command line as follows:

shell> mysqldump --tab=dir_name options db_name tbl_name ...

db_name names the database containing the table to be exported and tbl_name names the

table to be exported. To export multiple tables, name all of them following the database

name. If you don’t provide any table names, mysqldump exports all tables in the database.

 The options part of the mysqldump command may include any of the standard connection

parameter options, such as --host or --user. You’ll need to supply these options if the

default connection parameters aren’t appropriate. mysqldump also understands options specif-

ic to its own operation. Invoke mysqldump with the --help option to see a complete list of the

options that can be used to tell mysqldump the actions you want it to perform.

Suppose that you dump the table City from the world database using the /tmp directory as

the output directory:

shell> mysqldump --tab=/tmp world City

Page 17: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 17/18

27115.3 Importing and Exporting Data from the Command Line

 The output consists of a City.sql file containing the CREATE TABLE statement for the table,

and a City.txt file containing the table data.

 To reload data exported by invoking mysqldump with the --tab option, change location into

the dump directory. Then use mysql to process the .sql file that contains the CREATE TABLEstatement, and use mysqlimport to load the .txt file that contains the table data:

shell> cd /tmp

shell> mysql world < City.sql

shell> mysqlimport world City.txt

Using --tab to produce tab-delimited dump files is much faster than creating SQL-format 

files, but you should keep in mind the following points:

n  The CREATE TABLE statement for each table table_name is sent by the server to

mysqldump, which writes it to a file named table_name.sql in the dump directory on the

client host. The .sql files are owned by you.

n  The table contents are written directly by the server into a file named table_name.txt

in the dump directory on the server host. The .txt files are owned by the server.

n Use of --tab can be confusing because some files are created by the client and some by 

the server, and because the .sql files have different ownerships than the .txt files. To

minimize confusion, run mysqldump on the server host, specify the dump directory using

its full pathname so that mysqldump and the server both interpret it as the same location,

and specify a dump directory that is writable both to you and to the server.

n  The MySQL account that you use for connecting to the server must have the FILE

privilege because the dump operation causes the server to write data files on the server

host.n  To create only the data files and not the .sql files that contain the CREATE TABLE state-

ments, use the --no-create-info option.

 The default data file format produced by the --tab option consists of tab-delimited lines

 with newline terminators. This is the same default format assumed by the SELECT … INTO

OUTFILE statement. To control the format of the data files that mysqldump generates, use the

following options:

n --lines-terminated-by=string 

string specifies the character sequence that each input line should end with. The

default is \n (linefeed, also known as newline). Other common line terminators are \r

(carriage return) and \r\n (carriage return/linefeed pairs).

n --fields-terminated-by=string 

string specifies the delimiter to write between data values within input lines. The

default delimiter is \t (tab).

Page 18: My sql Study guide chapter 15

7/29/2019 My sql Study guide chapter 15

http://slidepdf.com/reader/full/my-sql-study-guide-chapter-15 18/18

272 CHAPTER 15 Importing and Exporting Data

n --fields-enclosed-by=char or --fields-optionally-enclosed-by=char 

char indicates a quote character that should be written surrounding data values. By 

default, values are not quoted. A common value for char is the double quote character

(‘“’). With --fields-enclosed-by, all values are quoted. With --fields-optionally-

enclosed-by, only values from string columns are quoted.

n --fields-escaped-by=char 

By default, special characters in data values are written preceded by ‘\’ as an escape

character, and NULL values are written as \N. Use this option to specify a different escape

character. To turn escaping off (no escape character), specify an empty value for char .

 The mysqlimport program has similar options for describing the data file format. See the

discussion of that program for information about specifying char or string  values that con-

tain characters that your command interpreter considers special.

If you combine the --tab option with format-control options such as --fields-terminated-by and --fields-enclosed-by, you should specify the same format-control options with

mysqlimport so that it knows how to interpret the data files.

 The --all-databases and --databases options for mysqldump are used for dumping multiple

databases. You cannot use those options together with --tab, which causes mysqldump to

 write the files for all dumped tables to a single directory. You would have no way to tell

 which files correspond to tables in each database.