一,数据从HDFS中导出至MySQL中
1)开启Hadoop、mysql进程
start-all.sh/etc/init.d/mysqld start/etc/init.d/mysqld status
2)将学生数据stu_data.csv传到HDFS的/local_student目录下
在hdfs中创建目录
hdfs dfs -mkdir /local_student
上传自定义的本地数据
hdfs dfs -put /root/lab/data/stu_data.csv /local_student/
注意:若出现以下错误:mkdir: Cannot create directory /student. Name node is in safe mode.
解决方案:hadoop dfsadmin -safemode leave
3)运行MySQL,创建数据库student_data,创建hdfs_stu_score_mysql表。
进入MySQL:mysql -uroot -p123456(-u表示用户名,-pbiaosh)
create database student_data;show databases;use student_data;create table hdfs_stu_score_mysql(id int not null primary key,name varchar(255),age int,score int);退出客户端:exit;
4)通过Sqoop,将HDFS上的数据导出到MySQL的hdfs_stu_score_mysql表中,具体命令如下:
sqoop export \--connect jdbc:mysql://127.0.0.1:3306/student_data \--username root \--password 123456 \--table hdfs_stu_score_mysql \
//--m 1 表示reduce数量定义为1个
--m 1 \--export-dir /local_student/ \
//文件以制表符为分割符
--input-fields-terminated-by '\t' \--columns="id,name,age,score"
5)MySQL中查询hdfs_stu_score_mysql表中数据
use student_data;select * from hdfs_stu_score_mysql;
二,数据从MySQL中导入至HDFS中
1)在MySQL中筛选分数在85分(包括85分)以上的学生信息
# 进入MySQL客户端mysql -uroot -p123456use student_data;# MySQL中建表create table mysql_stu_top(id int not null primary key,name varchar(255),age int,score int);# 插入数据到mysql_stu_top表中:insert into mysql_stu_top select * from hdfs_stu_score_mysql where score>=85;# 查看结果select * from mysql_stu_top;# 退出客户端:exit;
2)将MySQL中的mysql_stu_top表中数据导入到HDFS
sqoop import \--connect jdbc:mysql://127.0.0.1:3306/student_data \--username root \--password 123456 \--table mysql_stu_top \--m 1 \--target-dir /student/mysql_stu_top_hdfs
3)查看导入至HDFS中的数据
hdfs dfs -cat /student/mysql_stu_top_hdfs/part-m-00000