Search the MySQL manual:
MySQL Manual

Buy this Reference Manual in softcover from Barnes & Noble!

/ / Up / Table of Contents

3.3.3 Загрузка данных в таблицу

Создав таблицу, нужно позаботиться об ее заполнении. Для этого предназначены команды LOAD DATA и INSERT.

Предположим, ваши записи соответствуют приведенным в этой таблице (обратите внимание: MySQL принимает даты в формате ГГГГ-ММ-ДД; возможно, к такой записи вы не привыкли).

name owner species sex birth death
Fluffy Harold cat f 1993-02-04
Claws Gwen cat m 1994-03-17
Buffy Harold dog f 1989-05-13
Fang Benny dog m 1990-08-27
Bowser Diane dog m 1998-08-31 1995-07-29
Chirpy Gwen bird f 1998-09-11
Whistler Gwen bird 1997-12-09
Slim Benny snake m 1996-04-29

Так как вы начинаете работу с пустой таблицей, заполнить ее будет проще всего, если создать текстовый файл, содержащий по строке на каждое из животных, а затем загрузить его содержимое в таблицу одной командой.

Создайте текстовый файл с именем `pet.txt', содержащий по одной записи в каждой строке (значения столбцов должны быть разделены символами табуляции и даны в том порядке, который был определен командой CREATE TABLE). Незаполненным полям (например, неизвестный пол или даты смерти живых на сегодняшний день животных), можно присвоить значение NULL. В текстовом файле это значение представляется символами \N. Например, запись для птицы Whistler должна выглядеть примерно так (между значениями должны располагаться одиночные символы табуляции):

name owner species sex birth death
Whistler Gwen bird \N 1997-12-09 \N

Загрузить файл `pet.txt' в таблицу можно с помощью следующей команды:

mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet;

Маркер конца строки и символ, разделяющий значения столбцов, можно специально задать в команде LOAD DATA, но по умолчанию используются символы табуляции и перевода строки. Воспринимая их, команда сможет корректно прочитать файл `pet.txt'.

При добавлении одиночных записей используется команда INSERT. В самом простом варианте ее применения необходимо задать значения каждого столбца, в том порядке, в каком они были перечислены в команде CREATE TABLE. Предположим, Диана (Diane) купила хомячка по имени Puffball. Соответствующую запись в таблицу с можно внести с помощью команды INSERT примерно так:

mysql> INSERT INTO pet
    -> VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL);

Обратите внимание на то, что здесь строковые выражения и даты представлены в виде ограниченных кавычками строк. Кроме того, в команде INSERT отсутствующие данные можно прямо заменять на NULL. Пользоваться эвфемизмом \N, как в команде LOAD DATA, нужды нет.

Этот пример наглядно показывает, что если бы с самого начала все данные вносились в базу при помощи нескольких команд INSERT, а не одной команды LOAD DATA, то набирать пришлось бы гораздо больше текста.

User Comments

Posted by Jae K on Tuesday January 29 2002, @8:30am [Delete] [Edit]

for some reason it seems that when using files
to input data into tables, there must always be
a tab after the \N (for null).

this is true even when the null item is the last
item on the row. so, if you're getting 0000-00-
00 for the date in this example, try putting an
extra tab at the end of the line.

Posted by on Saturday March 2 2002, @5:46pm [Delete] [Edit]

load data has been disabled by default. use the
--local-infile option when starting mysql:

shell$ mysql --local-infile -p menagerie

mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE
pet;
Query OK, 8 rows affected (0.09 sec)
Records: 8 Deleted: 0 Skipped: 0 Warnings: 2


Now it works.

Posted by on Friday May 24 2002, @7:49am [Delete] [Edit]

I was desperately stuck because using files to
input data did not work ("SELECT * FROM ..."
always resulted in a deranged table). Jae K's
hint to put an extra tab after "\N"-entries in
the end of a row helped a bit, so I put an extra
tab in the end of each row, even if the last
entry was not "\N" - and this works! I get
some "warnings" when loading such a file, but the
result of "SELECT * FROM ..." now is as expected.

Posted by e w on Saturday November 16 2002, @11:56am [Delete] [Edit]

I fixed error that says used command not supported
by this version and loaded my data file by doing the
following:

mysql> --local-infile (May not be necessary)
mysql> use database_name
Database changed
mysql> LOAD DATA INFILE "tabledata.txt" INTO
TABLE table_name;
Query OK, 7 rows affected (0.02 sec)
Records: 7 Deleted: 0 Skipped: 0 Warnings: 7

Note: do NOT WRITE LOCAL in the previous load
data command as instructed in the sql manual.

Note: Place the data file in the folder with the name
of the database that has the table you want to load
data into; Otherwise, specify the path of the data file
in the command.

Posted by Calvin Lam on Monday February 3 2003, @2:33am [Delete] [Edit]

For this command:

Load data local infile "pet.txt" into table pet;

didn't work and give an error message saying that the "used command is not allowed in this version of Mysql"

However, it worked when I took out the "local" from my command.

Posted by Jeff Slatone on Tuesday February 4 2003, @7:40pm [Delete] [Edit]

F.Y.I.

1. Windows distribution somehow DOES NOT include sample file pet.txt (!).

2. On Windows servers command:
LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet;
does not work, returning message:
ERROR 1148: The used command is not allowed with this MySQL version

(I am on ver.4.0.9 recommended for development!)

3. Yet, command:
LOAD DATA INFILE "pet.txt" INTO TABLE pet;
would compile properly but your "pet.txt" load file must be in ./mysql/data/menagerie/ directory.

I hope this would be mentioned in future documentation updates.

Posted by on Monday February 10 2003, @7:49am [Delete] [Edit]

Found you need to add \\ in filenames to get files to load from different paths.
LOAD DATA INFILE "C:\\mypath\\my_data.txt" INTO TABLE my_data;

Posted by Doug Hall on Monday February 17 2003, @3:11pm [Delete] [Edit]

With Apple OS X: Use the terminal's drag and drop capability to insert the full path of the import file. This cuts down on the amount of typing, if you don't want deal with adding the import file into MySQL's data folder.

example:
%mysql --local-infile -u -p
Enter password:
mysql>load data local infile '' into table ;

Posted by on Monday March 3 2003, @11:35am [Delete] [Edit]

I cannot figure out what I am doing wrong. Whenever I use this command, or any other script to import a file, it only imports the first line. I cannot figure out how to make it import the entire file.

I made sure that I am using the LOAD command, and not the INSERT command. It does the same thing when I use PhpMyAdmin.

Any help would be greatly appreciated!

Add your own comment.

Top / / / Up / Table of Contents