【数据导入】
-
作用:
把文件系统的内容导入到数据库中 -
语法格式:
load data infile “文件名”
into table 表名
fields terminated by “分隔符”
lines terminated by "\n" -
示例:
把 /etc/passwd 文件中的内容导入到db3下的userinfo表
tarena : x : 1000 : 1000 :
用户名 密码 uid gid
tarena, : /home/tarena : /bin/bash
用户描述 主目录 登录权限 -
操作步骤:
- 在数据库中创建对应的表
create table userinfo( username varchar(20), password char(1), uid int, gid int, comment varchar(50), homedir varchar(50), shell varchar(50) )character set utf8;
- 把要导入的文件拷贝到数据库搜索路径中
- 查看数据库搜索路径
show variables like “secure_file_priv”; - sudo cp /etc/passwd /var/lib/mysql-files/
- 查看数据库搜索路径
- 执行数据库导入语句
load data infile "/var/lib/mysql-files/passwd" into table userinfo fields terminated by ":" lines terminated by "\n";
-
示例:
导入文件AID1709.csv一张成绩表1.在数据库中创建表 create table aid1709( id int, name varchar(20), score float(5,2), phone bigint, class char(7) )character set utf8; 2.拷贝文件(另起终端) sudo cp ~/AID1709.csv /var/lib/mysql-files/ #(~代表当前用户的主目录) #(路径要以绝对路径) 3.执行数据导入语句: load data infile "/var/lib/mysql-files/AID1709.csv" into table aid1709 fields terminated by "," lines terminated by "\n";
【数据导出】
-
作用:
将数据库中表记录保存到系统文件里 -
语法格式:
select …from 表名
into outfile “文件名”
fields terminated by “分隔符”
lines terminated by "\n"
(# 文件名要以绝对路径) -
示例:
1.把aid1709表中id,name,class三个字段的值给导出来 select id,name,class from aid1709 into outfile "/var/lib/mysql-files/student.txt" fields terminated by " " lines terminated by "\n"; 2.在终端中执行: sudo -i cd /var/lib/mysql-files/ ls 查看 cat student.txt(文件名)
-
注意:
- 导出的内容由SQL查询语句绝对
- 执行导出命令时路径必须指定对应的数据库目录下
-
修改读写权限:
chmod 777 文件名(最高权限了)
chmod +rw 文件名