本文将演示怎样使用 mysql 的 load data 命令批量导入数据。
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
在桌面上创建一个 data.txt 文件,文件内容如下:
1,Helen 2,Tom 3,Bill 4,Cay 5,Gary
打开 mysql 的客户端,连接到 mysql 服务器,运行 load data infile ** into table ** 命令,下面命令将每行当做数据表一行,字段间使用逗号分割,如下:
mysql> load data infile 'C:\\Users\\Administrator\\Desktop\\user.txt' into table user fields terminated by ','; Query OK, 5 rows affected (0.01 sec) Records: 5 Deleted: 0 Skipped: 0 Warnings: 0
验证刚刚导入的5条数据,如下:
mysql> select * from user; +----+-------+ | id | name | +----+-------+ | 1 | Helen | | 2 | Tom | | 3 | Bill | | 4 | Cay | | 5 | Gary | +----+-------+ 5 rows in set (0.07 sec)
在执行导入数据时,抛出如下错误:
mysql> load data infile 'C:\\Users\\Administrator\\Desktop\\user.txt' into table user fields terminated by ','; ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
执行导入命令出现了“The MySQL server is running with the --secure-file-priv option so it cannot execute this statement”错误。该错误是由于 secure-file-priv 变量的默认设置为 NULL 所引起的,该值意味着只能导出到指定目录下(已验证),否则会报错。使用如下命令查看 mysql 数据库该变量值:
mysql> show variables like '%secure%'; +--------------------------+-------+ | Variable_name | Value | +--------------------------+-------+ | require_secure_transport | OFF | | secure_auth | ON | | secure_file_priv | NULL | +--------------------------+-------+ 3 rows in set (0.04 sec)
解释:
(1)secure_file_prive=null,限制 mysqld 不允许导入导出
(2)secure_file_priv=/var/lib/mysql-files/,限制 mysqld 的导入导出只能发生在 /var/lib/mysql-files/ 目录下
(3)secure_file_priv=' ',不对 mysqld 的导入导出做限制
通过修改 my.ini 文件,添加如下内容:
[mysqld] # ... 下面行内容 secure_file_priv=''
然后,重启 MySQL 服务,再次查看 secure-file-priv 变量的值,如下:
mysql> show variables like '%secure%'; +--------------------------+-------+ | Variable_name | Value | +--------------------------+-------+ | require_secure_transport | OFF | | secure_auth | ON | | secure_file_priv | | +--------------------------+-------+ 3 rows in set (0.04 sec)