数据导入
- 作用
把文件系统的内容导入到数据库中 - 语法(方式一)
load data infile "文件名"
into table 表名
fields terminated by "分隔符"
lines terminated by "\n"
示例
scoretable.csv文件导入到数据库db2的表
1、将scoretable.csv放到数据库搜索路径中
mysql>show variables like 'secure_file_priv';
/var/lib/mysql-files/
Linux: sudo cp /home/tarena/scoreTable.csv /var/lib/mysql-files/
2、在数据库中创建对应的表
create table scoretab(
rank int,
name varchar(20),
score float(5,2),
phone char(11),
class char(7)
)charset=utf8;
3、执行数据导入语句
load data infile '/var/lib/mysql-files/scoreTable.csv'
into table scoretab
fields terminated by ','
lines terminated by '\n';
4、ID位数不够补零
添加id字段,要求主键自增长,显示宽度为3,位数不够用0填充
alter table scoretab add id int(3) zerofill primary key auto_increment first;
- 语法(方式二)
source 文件名.sql
数据导出
- 作用
将数据库中表的记录保存到系统文件里 - 语法格式
select ... from 表名
into outfile "文件名"
fields terminated by "分隔符"
lines terminated by "分隔符";
- 示例
1、把sanguo表中英雄的姓名、攻击值和国家三个字段导出来,放到 sanguo.csv中 并将导出的文件移到/home/teenjeen/
select name, attack, country from country.sanguo
into outfile '/home/teenjeen/sanguo.csv'
fields terminated by ','
lines terminated by '\n';
2、将mysql库下的user表中的 user、host两个字段的值导出到 user2.txt,将其存放在数据库目录下
select user, host from mysql.user
into outfile '/var/lib/mysql-files/user2.txt'
fields terminated by ' '
lines terminated by '\n';
- 注意
1、导出的内容由SQL查询语句决定
2、执行导出命令时路径必须指定在对应的数据库目录下
表的复制
1、表能根据实际需求复制数据
2、复制表时不会把KEY属性复制过来
- 语法
create table 表名 select 查询命令;
- 示例
1、复制sanguo表的全部记录和字段,sanguo2
create table sanguo2 select * from sanguo
2、复制sanguo表的 id,name,country 三个字段的前3条记录,sanguo3
create table sanguo3 select id,name,country from sanguo limit 3
-
注意
复制表的时候不会把原有表的 KEY 属性复制过来 -
复制表结构
create table 表名 select 查询命令 where false;