将csv文件导入mysql

1.数据准备

将手头的excel或者number数据另存为.csv文件,方便后面的导入

2.数据库的准备

这里登录数据库,选择对应的database,然后再创建相应的表,这里要注意表的字段类型和数目要和csv文件对应

create table `r_vn_city_level`(
city char(64) not null,
level char(10) not null,
primary key (`city`,`level`))
charset utf8;

3.导入数据

这里是最关键的一步,也最容易出错,先看导入的命令:

load data infile '/home/python/Desktop/test.csv'
into table r_vn_city_level
fields terminated by ',' optionally enclosed by '"' escaped by '"'
lines terminated by '\r\n';

如果就这样导入会出错,错误如下:

The MySQL server is running with the --secure-file-priv option so it cannot execute this statement 

输入命令:

show global variables like '%secure%';

这里secure_file_priv这个字段可能有三种值:

  • ure_file_priv的值为null ,表示限制mysqld 不允许导入|导出

  • 当secure_file_priv的值为/tmp/ ,表示限制mysqld 的导入|导出只能发生在/tmp/目录下

  • 当secure_file_priv的值没有具体值时,表示不对mysqld 的导入|导出做限制

所以我们需要对其进行设置,这里我们vim打开mysql的配置文件,我这里的命令如下:

进入配置文件后,将secure_file_priv添加或者修改为:

secure_file_priv=''

然后保存关闭,重启mysql服务,终端输入:

service mysql restart

这时重新输入导入文件的命令,别急,还会报错:

大致意思就是说找不到这个文件,可是明明路径是对的呀,怎么解决呢?很简单,只需要加上local这个命令:

load data local infile '/home/python/Desktop/test.csv'
into table r_vn_city_level
fields terminated by ',' optionally enclosed by '"' escaped by '"'
lines terminated by '\r\n';

接下来再执行一遍,就可以导入成功了!

猜你喜欢

转载自www.cnblogs.com/daigua/p/9863472.html