曲径通幽论坛

标题: 使用 mysqlimport 导入数据 [打印本页]

作者: beyes    时间: 2012-4-28 11:32
标题: 使用 mysqlimport 导入数据
mysqlimport 是 MySQL 提供的导入工具,位于安装目录的 bin 目录下,它可以把一个文本文件(Text File)导入到用户指定的数据表中。

mysqlimport 有两个基本参数和大量的可选参数,其基本语法格式为:
mysqlimport [-d/-f...] db_name data.txt
其中,[-d/-f...] 表示可选参数,db_name 表示数据库名称,data.txt 表示记录的文本文件。将文本导入到数据库的命令格式如下:
mysqlimport -uroot -pgroad -hlocalhost books data_import.txt

下面是几个常用可选参数的说明:
-d : 在新数据导入数据表之前删除掉表中的原有数据。
-f :不管执行过程中是否有错误,mysqlimport 仍将强制继续插入数据。
-i :mysqlimport 跳过或忽略那些有相同唯一关键字的行,即重复记录不导入。
-r :该选项和 -i 相反,用于替代表中有唯一关键字的记录。
-lock_tables : 数据被插入之前锁住表。

下面是一个简单示例:

1. 查看某个数据库的数据表:
mysql> use bookstore;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

mysql> show tables;
+---------------------+
| Tables_in_bookstore |
+---------------------+
| authors             |
| books               |
+---------------------+
2 rows in set (0.00 sec)

mysql> desc authors;
[attach]373[/attach]

2. 根据 authors 这个表格式构建一个记录文本,内容如下:
$ cat authors.txt
4    Lee    Tony    China
5    Wong    Jimy    USA
6    Chou    Lily    JAPAN
7    Gou    Ben    UK
想将该文件拷贝到以下目录:
# cp authors.txt /var/lib/mysql/bookstore/
该目录为 bookstore 数据库所对应的目录,如果不是这样,会看到找不到导入文件的错误信息:
$ mysqlimport -uroot -p123456 -hlocalhost bookstore authors.txt
mysqlimport: Error: 13, Can't get stat of '/var/lib/mysql/bookstore/authors.txt' (Errcode: 2), when using table: authors

现在可以将文本导入到数据库中了:
# mysqlimport -uroot -p123456 -hlocalhost bookstore authors.txt
bookstore.authors: Records: 4  Deleted: 0  Skipped: 0  Warnings: 0

查询导入是否成功:
mysql> select * from authors;
[attach]372[/attach]
由上可见,数据准确无误的导入。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2