MySQL导入csv数据
前言
下载了一个数据组,数据格式是CSV,再导入过程中遇到了问题
一、导入步骤
1.MySQL workbench 操作语句
我用的是MySQL workbench,建立一个数据库用来存放数据,新建空表格(表格的列数要和导入数据的相同),用来导入数据,我这里需要导入3个表格,所以就建了3各表:
create database if not exists a
use a;
#show create database a 显示创建的数据库的属性
DROP table if exists users;
create table users
(user_id varchar(20) not null,
register_time varchar(50) null,
recently_logged varchar(50) null,
number_of_classes_join varchar(20) null ,
number_of_classes_out varchar(20) null ,
learn_time varchar(20) null,
school varchar(50) null
) ;
/*load data local infile'D:/Personal/user.csv'
into table users
FIELDS TERMINATED BY ','
ENCLOSED BY ""
LINES TERMINATED BY '\n'
ignore 1 rows;*/导入数据步骤,需要在cmd中运行,
DROP table if exists study_information;
create table study_information
(user_id varchar(20) primary key not null,
course_id varchar(50) null,
course_join_time datetime null,
learn_process varchar(20) null ,
price varchar(20) null
) ;
# desc study_information 显示创建的表
DROP table if exists login;
CREATE TABLE login (
user_id VARCHAR(20) NOT NULL,
login_time DATETIME NULL,
login_place VARCHAR(20) NULL
);
2.用CMD命令窗口导入数据
注意打开cmd窗口时要用管理员身份打开
#1.登录服务器
C:\WINDOWS\system32>net start mysql80 #因为我装的是mysql8.0所以是MySQL80
请求的服务已经启动。
请键入 NET HELPMSG 2182 以获得更多的帮助。
#2.登录账户
C:\WINDOWS\system32>mysql -uroot -p
Enter password: **********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 29
Server version: 8.0.27 MySQL Community Server - GPL
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
#3.查看客户端 local_infile的状态,未开启的为OFF,利用set global local_infile=on;开启即可;
mysql> show variables like'%local_infile%';#注意这里的符号必须得是英文状态下的符号
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile | ON |
+---------------+-------+
1 row in set, 1 warning (0.00 sec)
#4.退出MySQL
mysql> \q
Bye
#5.以mysql -u 用户名 --local-infile=1 -p登录MySQL
C:\WINDOWS\system32>mysql -u root --local-infile=1 -p
Enter password: ********
#6.调用数据库并导入数据
mysql> use a;
Database changed
mysql> set global local_infile=1;
Query OK, 0 rows affected (0.00 sec)
mysql> load data local infile'D:\\Personal\\users-1.csv' #注意windows 系统下,文件的路径要一定要用\表示
into table users
fields terminated by ','
enclosed by ""
lines terminated by '\n'
ignore 1 rows ;
#文件的字段由FIELD TERMINATED BY ','指示的逗号终止,并由ENCLOSED BY '"'指定的双引号括起来。因为文件第一行包含列标题,列标题不需要导入到表中,因此通过指定IGNORE 1 ROWS选项来忽略第一行。
Query OK, 43983 rows affected, 7391 warnings (0.34 sec)
Records: 43983 Deleted: 0 Skipped: 0 Warnings: 7391
SELECT * FROM discounts #查看是否导入数据,也可以在MySQL workbench 中查看
3.用cmd时犯的一个错误
ERROR 1300 (HY000): Invalid utf8mb4 character string: '?\00FB'
这个问题的解决方法是:将文件转换uft8的形式即可
总结
符号必须是英文符号。
本文介绍了如何使用MySQL Workbench和CMD命令窗口导入CSV数据,包括创建匹配的数据库表格,解决CMD导入时的字符编码问题,强调了使用英文符号的重要性。

2333

被折叠的 条评论
为什么被折叠?



