Search the MySQL manual:
Subscribe to the monthly
MySQL Newsletter!

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 Doug Hall on 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 <username> -p <DatabaseName>
Enter password:<password>
mysql>load data local infile '<drag input file here>' into table <TableName>;

Posted by Janusz Ole&#347; on August 3 2003 3:11am[Delete] [Edit]

mysql> LOAD DATA INFILE '/path/to/your/tblpet.txt' INTO TABLE tblpet;
ERROR 13: Can't get stat of '/path/to/your/tblpet.txt' (Errcode: 13)
NOTE:
All directories within the path to the target destination must be flagged 755
or higher, otherwise mysql will not be allowed to access destination file.
So if you run into this (ERROR 13) simply check each directory within the path
and make sure of it's settings.

Posted by steve pratt on December 23 2003 9:50am[Delete] [Edit]

Version 4.0.17 on Windows NT cannot specify path\filename in a LOAD statement. I specified "bin\b.txt" and got ERROR file 'bi.txt' not found. In a later chapter we learn that you specify path like this "bin/b.txt". Then it works fine.

Posted by Daniel Leibacher on January 2 2004 2:08pm[Delete] [Edit]

In all the documentation to load data into tables there's always the similar example with only the filename ("pet.txt") like in the above example:

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

In fact you have to specify the full path where the file can be found. E.g. "c:/mysql/data/pet.txt"


Posted by [name withheld] on January 19 2004 7:24pm[Delete] [Edit]

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

Works perfectly when "pet.txt" is in your working directory, at least when connecting from "localhost".

Posted by Maurice Lanselle on January 20 2004 5:37am[Delete] [Edit]

On Win XP, I confirm I had to enter the full path with "LOAD DATA LOCAL INFILE..." or put the file in the mysql\bin\ folder (after I had tried putting the "pet.txt" file in several different folders and still gotten "ERROR ...(Errcode: 2)). An alternative is to put the file in the ".\data\menagerie" folder (for the database) where it is considered to be on the server and use "LOAD DATA INFILE" (without LOCAL, which does the load from server rather than from client).

It is good to know that one can specify a path with the LOCAL option. This was not obvious for me from the manual.

Posted by Serge LAOT on March 2 2004 9:28am[Delete] [Edit]

On windows :
With LOAD DATA LOCAL INFILE, you must enter two backslahes instead of one (or use /) to specify the path of the file.

Add your own comment.