将csv文件导入到mysql

 

首先,为自己要导入的文件按照属性创建好表:

mysql> create table xxx( 
-> id int not null primary key,
 -> name char(30) character set utf8 not null, 
-> level char(30) character set utf8 not null,
 -> profession char(30) character set utf8 not null, 
-> work_unit char(100) character set utf8 not null 
-> ); 
Query OK, 0 rows affected, 4 warnings (0.02 sec)

 

注意,当表中的数字过大时,最好将其数据类型设置为字符型。我这里开始时设置为INT,也就是4个字节,结果报错了。

所以我又将其修改了下:

mysql> alter table qulification modify id varchar(100);

 

导入CSV文件,我开始时将源文件保存在了普通文件夹里,结果报出安全错误:

mysql> load data infile '/home/xxx/xxx/xxx.csv' into table qulification fields terminated by ','; 

ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

 

 

解决办法1:

  • 查找MYSQL指定的安全导入导出文件夹:

  • mysql> show variables like "secure%"; 
    +------------------+-----------------------+ | 
       Variable_name | Value | 
    +------------------+-----------------------+ |
     secure_file_priv | /var/lib/mysql-files/ | 
    +------------------+-----------------------+

     

  • 复制源文件到指定文件夹 

    sudo cp xxx/xxx/xxx.csv /var/lib/mysql-files/

     

  • 将指定文件夹里的源文件导入MySQL:

  • `mysql> load data infile '/var/lib/mysql-files/xxx.csv' into table qulification fields terminated by ','; 
    
    Query OK, 3083 rows affected (0.19 sec) Records: 3083 Deleted: 0 Skipped: 0 Warnings: 0

     

 

解决办法2:

参照官网对这个字段的解释:

secure_file_priv may be set as follows:

  • If empty, the variable has no effect. This is not a secure setting.

  • If set to the name of a directory, the server limits import and export operations to work only with files in that directory. The directory must exist; the server will not create it.

  • If set to NULL, the server disables import and export operations.

可自行到Mysql的配置文件中修改相应字段。

 

 

posted @ 2020-10-02 14:35  minexy  阅读(577)  评论(0)    收藏  举报