Hadoop实验——NoSQL与关系型数据库的比较

实验目的

  1. 理解四种数据库(MySQL,HBase,Redis,MongoDB)的概念以及不同点。
  2. 熟练使用四种数据库操作常用的Shell命令。
  3. 熟悉四种数据库操作常用的Java API。

实验平台

  • 操作系统:Ubuntu-16.04
  • Hadoop版本:2.6.0
  • JDK版本:1.8
  • IDE:Eclipse
  • HBase版本:1.2.3
  • MySQL版本:5.7.16
  • MongoDB版本:2.6.10
  • Redis:版本:3.0.6
  • IDE:Eclipse

数据库的安装

  1. MySQL的安装
  2. 更新APT
    sudo apt-get update

  3. 打开终端,安装mysql-server
    sudo apt-get install mysql-server

  4. 输入密码


  5. 安装mysql-client
    sudo apt-get install mysql-client

  6. 安装libmysqlclient-dev
    sudo apt-get install libmysqlclient-dev

  7. 测试是否安装成功
    sudo netstat -tap | grep mysql
    通过上述命令检查之后,如果看到有mysql 的socket处于 listen 状态则表示安装成功。

  8. Redis的安装
  9. 安装redis-server
    sudo apt-get install redis-server

  10. 测试是否安装成功
    sudo netstat -tap|grep redis

  11. MongoDB的安装
  12. 安装mongodb-server
    sudo apt-get install mongodb-server

  13. 测试是否安装成功
    sudo netstat -tap|grep mongod

  14. HBase已经安装过了(详见http://www.jianshu.com/p/9ac6a4878b07

实验内容和要求

一,MySQL数据库操作:

<div align = center>student学生表 </div>

name English Math Computer
zhangsan 69 86 77
lisi 55 100 88
  1. 根据上面给出的表格,利用MySQL设计出student学生表格。
  2. 登陆MySQL(退出指令为quit)
    mysql -u root -p
    输入密码
  3. 创建数据库
    create database test;
  4. 使用数据库
    use test;
  5. 创建student表
create table student(
    name varchar(30) not null,
    English tinyint unsigned not null,
    Math tinyint unsigned not null,
    Computer tinyint unsigned not null
    );
  1. 初始化数据
    insert into student values("zhangsan",69,86,77);

    insert into student values("lisi",55,100,88);
  2. 查看student表
    select * from student;
  3. 查看zhangsan的Computer成绩
    select name , Computer from student where name = "zhangsan";
  4. 修改lisi的Math成绩,改为95
    update student set Math=95 where name="lisi";
  5. 根据上面已经设计出的student表,通过JDBC操作MySQL
  6. 添加数据:Name:scofield English:45 Math:89 Computer:100

Eclipse的使用
1. 找到 File 菜单,选择 New -> Java Project



1. 输入 Project name,然后Finish



1. 点开项目,找到 src 文件夹,右键选择 New -> Class

1. 输入 Package 和 Name,然后Finish

1. 将jar包从主机拉到虚拟机中的Home



1. 右键工程,选择 Properties ,然后在工程中导入外部jar包


1. 写好Java代码(填上密码),右键选择 Run As -> Java Application,就可以在Console里看到结果了

JAVA代码:
package com.mysql;
import java.sql.*;
public class MysqlTest {
   static final String DRIVER = "com.mysql.jdbc.Driver";
   static final String DB = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
   static final String USER = "root";
   static final String PASSWD = "";
   public static void main(String[] args) {
       Connection conn = null;
       Statement stmt = null;
       try {
           Class.forName(DRIVER);
           System.out.println("Connecting to a selected database...");
           conn = DriverManager.getConnection(DB, USER, PASSWD);
           stmt = conn.createStatement();
           String sql = "insert into student values('scofield',45,89,100)";
           stmt.executeUpdate(sql);
           System.out.println("Inserting records into the table successfully!");
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       } catch (SQLException e) {
           e.printStackTrace();
       } finally {
           if (stmt != null)
               try {
                   stmt.close();
               } catch (SQLException e) {
                   e.printStackTrace();
               }
           if (conn != null)
               try {
                   conn.close();
               } catch (SQLException e) {
                   e.printStackTrace();
               }
       }
   }
}
  1. 插入数据之后,MySQL客户度查询结果如下
  1. 获取scofield的English成绩信息

JAVA代码:

package com.mysql;
import java.sql.*;
public class MysqlTest2 {

    static final String DRIVER = "com.mysql.jdbc.Driver";
    static final String DB = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
    static final String USER = "root";
    static final String PASSWD = "0822";

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName(DRIVER);
            System.out.println("Connecting to a selected database...");
            conn = DriverManager.getConnection(DB, USER, PASSWD);
            stmt = conn.createStatement();
            String sql = "select name,English from student where name='scofield' ";
            rs = stmt.executeQuery(sql);
            System.out.println("name" + "\t\t" + "English");
            while (rs.next()) {
                System.out.print(rs.getString(1) + "\t\t");
                System.out.println(rs.getInt(2));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null)
                try {
                    rs.close();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            if (stmt != null)
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            if (conn != null)
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }
}

Eclipse控制台输出如下:


二,HBase数据库操作:

<div align = center>student学生表 </div>

name score:English score:Math score:Computer
zhangsan 69 86 77
lisi 55 100 88
  1. 根据上面给出的表格,用Hbase Shell模式设计student学生表格。
  2. 启动 Hadoop
    • 进入 Hadoop 主文件夹
      cd /usr/local/hadoop/
    • 开启 Hadoop 相关进程
      sbin/start-dfs.sh

      sbin/start-yarn.sh
  3. 启动 HBase
    • 进入HBase主文件夹
      cd /usr/local/hbase/
    • 开启HBase相关进程
      bin/start-hbase.sh
  4. 进入 Hbase Shell(退出指令为quit
  5. 创建表student表


  6. 初始化student表
put 'student','zhangsan','score:English','69'
put 'student','zhangsan','score:Math','86'
put 'student','zhangsan','score:Computer','77'
put 'student','lisi','score:English','55'
put 'student','lisi','score:Math','100'
put 'student','lisi','score:Computer','88'
  1. 查看student表
    scan 'student'
  2. 查询zhangsan 的Computer成绩
    get 'student','zhangsan','score:Computer'
  3. 修改lisi的Math成绩,改为95
    put 'student','lisi','score:Math','95'
  4. 根据上面已经设计出的student表,用Hbase API操作MySQL
  5. 添加数据:Name:scofield English:45 Math:89 Computer:100
    1. 点开项目,找到 src 文件夹,右键选择 New -> Class


    2. 输入 Package 和 Name,然后Finish


    3. 右键工程,选择 Properties ,然后在工程中导入外部jar包



      JAVA代码:

package com.hbase;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
public class HbaseTest {
   public static Configuration configuration;
   public static Connection connection;
   public static Admin admin;
   public static void main(String[] args) {
       configuration = HBaseConfiguration.create();
       configuration.set("hbase.rootdir", "hdfs://localhost:9000/hbase");
       try {
           connection = ConnectionFactory.createConnection(configuration);
           admin = connection.getAdmin();
       } catch (IOException e) {
           e.printStackTrace();
       }
       try {
           insertRow("student", "scofield", "score", "English", "45");
           insertRow("student", "scofield", "score", "Math", "89");
           insertRow("student", "scofield", "score", "Computer", "100");
       } catch (IOException e) {
           e.printStackTrace();
       }
       close();
   }
   public static void insertRow(String tableName, String rowKey,
           String colFamily, String col, String val) throws IOException {
       Table table = connection.getTable(TableName.valueOf(tableName));
       Put put = new Put(rowKey.getBytes());
       put.addColumn(colFamily.getBytes(), col.getBytes(), val.getBytes());
       table.put(put);
       table.close();
   }
   public static void close() {
       try {
           if (admin != null) {
               admin.close();
           }
           if (null != connection) {
               connection.close();
           }
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}
  1. 插入数据之后,HBase Shell查询结果如下
  1. 获取scofield的English成绩信息

JAVA代码:

package com.hbase;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
public class HbaseTest2 {
    public static Configuration configuration;
    public static Connection connection;
    public static Admin admin;

    public static void main(String[] args) {
        configuration = HBaseConfiguration.create();
        configuration.set("hbase.rootdir", "hdfs://localhost:9000/hbase");
        try {
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            getData("student", "scofield", "score", "English");
        } catch (IOException e) {
            e.printStackTrace();
        }
        close();
    }

    public static void getData(String tableName, String rowKey,
            String colFamily, String col) throws IOException {
        Table table = connection.getTable(TableName.valueOf(tableName));
        Get get = new Get(rowKey.getBytes());
        get.addColumn(colFamily.getBytes(), col.getBytes());
        Result result = table.get(get);
        showCell(result);
        table.close();
    }

    public static void showCell(Result result) {
        Cell[] cells = result.rawCells();
        for (Cell cell : cells) {
            System.out.println("RowName:" + new String(CellUtil.cloneRow(cell))
                    + " ");
            System.out.println("Timetamp:" + cell.getTimestamp() + " ");
            System.out.println("column Family:"
                    + new String(CellUtil.cloneFamily(cell)) + " ");
            System.out.println("row Name:"
                    + new String(CellUtil.cloneQualifier(cell)) + " ");
            System.out.println("value:" + new String(CellUtil.cloneValue(cell))
                    + " ");
        }
    }

    public static void close() {
        try {
            if (admin != null) {
                admin.close();
            }
            if (null != connection) {
                connection.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Eclipse控制台输出如下:


三,Redis数据库操作:

student 键值对:

zhangsan:{
English: 69
Math: 86
Computer: 77
}
lisi:{
English: 55
Math: 100
Computer: 88
}
  1. 根据上面给出的键值对,利用哈希结构设计出上述表格。(键值可以用student.zhangsan,student.lisi来表示两个键值属于同一个表格)
  2. 启动Redis客户端(退出指令为quit)
    redis-cli
  3. 设计上述表格
hset student.zhangsan English 69
hset student.zhangsan Math 86
hset student.zhangsan Computer 77
hset student.lisi English 55
hset student.lisi Math 100
hset student.lisi Computer 88
  1. 输出zhangsan和lisi的信息
    hgetall student.zhangsan

    hgetall student.lisi
  2. 查看zhangsan的Computer成绩
    hget student.zhangsan Computer
  3. 修改lisi的Math成绩,改为95
    hset student.lisi Math 95
  4. 根据上面已经设计出的student表,通过jedis操作Redis
  5. 添加数据:
scofield:{
English: 45
Math: 89
Computer: 100
}
  1. 点开项目,找到 src 文件夹,右键选择 New -> Class

1. 输入 Package 和 Name,然后Finish



1. 将jar包从主机拉到虚拟机中的Home



1. 右键工程,选择 Properties ,然后在工程中导入外部jar包

JAVA代码:
package com.redis;
import java.util.Map;
import redis.clients.jedis.Jedis;
public class RedisTest {
   public static void main(String[] args) {
       Jedis jedis = new Jedis("localhost");
       jedis.hset("student.scofield", "English", "45");
       jedis.hset("student.scofield", "Math", "89");
       jedis.hset("student.scofield", "Computer", "100");
       Map<String, String> value = jedis.hgetAll("student.scofield");
       for (Map.Entry<String, String> entry : value.entrySet()) {
           System.out.println(entry.getKey() + ":" + entry.getValue());
       }
   }
}
  1. 插入数据之后,Redis客户度查询结果如下
  1. 获取scofield的English成绩信息

JAVA代码:

package com.redis;
import redis.clients.jedis.Jedis;
public class RedisTest2 {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("localhost");
        String value = jedis.hget("student.scofield", "English");
        System.out.println("scofield's English score is:    " + value);
    }
}

Eclipse控制台输出如下:


四,MongoDB数据库操作:

student文档如下:

{
“name”: “zhangsan”,
“score”: {
“English”: 69,
“Math”: 86,
“Computer”: 77
}
}
{
“name”: “lisi”,
“score”: {
“English”: 55,
“Math”: 100,
“Computer”: 88
}
}
  1. 根据上面给出的文档,用Mongo shell设计出student集合
  2. 启动MongoDB客户端(退出指令为quit();)
    mongo
  3. 创建student数据库,
    use student
  4. 定义数组
var stus=[
      {"name":"zhangsan","scores":{"English":69,"Math":86,"Computer":77}},        
      {"name":"lisi","score":{"English":55,"Math":100,"Computer":88}} ]
  1. 插入到数据库
    db.student.insert(stus)
  2. 输出student的信息
    db.student.find().pretty()
  3. 查询zhangsan 的所有成绩(只显示score列)
    db.student.find({"name":"zhangsan"},{"_id":0,"name":0})
  4. 修改lisi的Math成绩,改为95
    db.student.update({"name":"lisi"}, {"$set":{"score.Math":95}} )
  5. 根据上面已经设计出的student集合,通过JDBC操作MongoDB
  6. 添加数据:
English:45  Math:89 Computer:100
{
“name”: “scofield”,
“score”: {
“English”: 45,
“Math”: 89,
“Computer”: 100
}
}
  1. 点开项目,找到 src 文件夹,右键选择 New -> Class

1. 输入 Package 和 Name,然后Finish



1. 将jar包从主机拉到虚拟机中的Home



1. 右键工程,选择 Properties ,然后在工程中导入外部jar包

JAVA代码:
package com.mongo;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoTest {
   public static void main(String[] args) {
       MongoClient mongoClient = new MongoClient("localhost", 27017);
       MongoDatabase mongoDatabase = mongoClient.getDatabase("student");
       MongoCollection<Document> collection = mongoDatabase
               .getCollection("student");
       Document document = new Document("name", "scofield").append(
               "score",
               new Document("English", 45).append("Math", 89).append(
                       "Computer", 100));
       List<Document> documents = new ArrayList<Document>();
       documents.add(document);
       collection.insertMany(documents);
       System.out.println("文档插入成功");
   }
}
  1. 插入数据之后,MongoDB客户度查询结果如下
  1. 获取scofield的English成绩信息

JAVA代码:

package com.mongo;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import static com.mongodb.client.model.Filters.eq;
public class MongoTest2 {
    public static void main(String[] args) {
        MongoClient  mongoClient=new MongoClient("localhost",27017);
        MongoDatabase mongoDatabase = mongoClient.getDatabase("student");
        MongoCollection<Document> collection = mongoDatabase.getCollection("student");
        MongoCursor<Document>  cursor=collection.find( new Document("name","scofield")).
                projection(new Document("score",1).append("_id", 0)).iterator();
        while(cursor.hasNext())
            System.out.println(cursor.next().toJson());
    }
}

Eclipse控制台输出如下:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,924评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,902评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,716评论 0 239
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,783评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,166评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,510评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,784评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,476评论 0 196
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,196评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,459评论 2 243
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,978评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,321评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,964评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,046评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,803评论 0 193
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,530评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,420评论 2 265

推荐阅读更多精彩内容

  • import org.apache.hadoop.conf.Configuration; import org.a...
    苏大鸿阅读 602评论 0 1
  • 泛型 对象和实例是一个意思,类与对象的关系就像数据类型和变量一样。 泛型的主要目的之一就是用来指定类(如:容器)要...
    yueyue_projects阅读 550评论 0 0
  • 琐事记10.6-10.8 昨天(10.5)下午,从荆州回来,下车之后,我走进家族内的一位哥哥家,想与他商量一件考虑...
    小棕榈阅读 204评论 0 0