3.1 导入数据

在 Sqoop 中, 数据的导入或者导出都是站在大数据集群的角度来看的:

如果把数据从非大数据集群(mysql)到大数据集群(HDFS,HIVE,HBASE) 叫做导入反之就是导出


3.1.1 从普通数据库(mysql) 到 HDFS

步骤1: 确认 Mysql 服务正常启动

sudo service mysql status

步骤2: 在 Mysql 中新建一张表并插入一些数据

create database company;
create table company.staff(id int(4) primary key not null auto_increment, name varchar(255), sex varchar(255));

insert into company.staff(name, sex) values('zangsan', 'Male');
insert into company.staff(name, sex) values('lisi', 'Male');
insert into company.staff(name, sex) values('wangwu', 'Male');
insert into company.staff(name, sex) values('zhiling', 'Male');
insert into company.staff(name, sex) values('fengjie', 'Male');

步骤3: 开始导入数据

1. 全部导入

sqoop import \
--connect jdbc:mysql://hadoop201:3306/company \
--username root \
--password aaa \
--table staff \
--target-dir /user/company \
--delete-target-dir \
--num-mappers 1 \
--fields-terminated-by "\t"

2. 查询导入(Free-form Query Imports)

sqoop import \
--connect jdbc:mysql://hadoop201:3306/company \
--username root \
--password aaa \
--target-dir /user/company \
--delete-target-dir \
--num-mappers 1 \
--fields-terminated-by "\t" \
--query 'select name,sex from staff where id <=2 and $CONDITIONS'

注意:

  • 使用 --query 的时候, 必须在 where 子句中添加 $CONDITIONS.
  • 如果 --query 后面跟的是双引号, 则需要使用 \$CONDITIONS.

3. 导入指定列

sqoop import \
--connect jdbc:mysql://hadoop201:3306/company \
--username root \
--password aaa \
--table staff \
--columns id,sex \
--target-dir /user/company \
--delete-target-dir \
--num-mappers 1 \
--fields-terminated-by "\t"

注意:

  • --columns 中如果涉及到多列用逗号分隔,分隔时不要添加空格. 否则会抛异常

4. 使用 sqoop 关键字筛选查询导入数据

sqoop import \
--connect jdbc:mysql://hadoop201:3306/company \
--username root \
--password aaa \
--where 'id=1' \
               \
--target-dir /user/company \
--delete-target-dir \
--num-mappers 1 \
--fields-terminated-by "\t" \
--table staff

3.1.2 从普通数据库(mysql) 到 Hive

sqoop import \
--connect jdbc:mysql://hadoop201:3306/company \
--username root \
--password aaa \
--table staff \
              \
--num-mappers 1 \
--hive-import \
--fields-terminated-by "\t" \
--hive-overwrite \
--delete-target-dir \
--hive-table staff_hive

注意:

  • 如果抛出异常:Could not load org.apache.hadoop.hive.conf.HiveConf. Make sure HIVE_CONF_DIR is set correctly, 则需要把$HIVE_HOME/lib/*加入到环境变量HADOOP_CLASSPATH

    sqopp-env.sh 下添加如下代码:

    export HADOOP_CLASSPATH=$HADOOP_CLASSPATH:$HIVE_HOME/lib/*
    
  • 该过程分为两步,第一步将数据导入到 HDFS,第二步将导入到 HDFS 的数据迁移到Hive 仓库,第一步默认的临时目录是/user/atguigu/表名


3.1.3 从普通数据库(mysql) 到 HBase

sqoop import \
--connect jdbc:mysql://hadoop201:3306/company \
--username root \
--password aaa \
--table staff \
              \
--hbase-table "hbase_company" \
--column-family "info" \
--columns "id,name,sex" \
--hbase-create-table \
--hbase-row-key "id" \
--num-mappers 1 \
--split-by id

Copyright © 尚硅谷大数据 2019 all right reserved,powered by Gitbook
该文件最后修订时间: 2019-03-30 12:29:57

results matching ""

    No results matching ""