大数据技术原理与应用实验3——NoSQL和关系数据库的操作比较

一、实验目的

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

二、实验环境

(1)Linux操作系统(CentOS7.5)
(2)VMware Workstation Pro 15.5
(3)远程终端工具Xshell7
(4)Xftp7传输工具
(5)Hadoop版本:3.1.3;
(6)HBase版本:2.2.2;
(7)JDK版本:1.8;
(8)Java IDE:Idea。
(9)MySQL版本:5.7;
(10)Redis版本:2.8.9;
(11)MongoDB版本:4.2.0;
(12)JDK版本:1.8;

三、实验内容

(一) MySQL数据库操作

学生表如14-7所示。
在这里插入图片描述

1. 根据上面给出的Student表,在MySQL数据库中完成如下操作:

(1)在MySQL中创建Student表,并录入数据;
创建Student表的SQL语句如下:

CREATE TABLE student(
    NAME VARCHAR(30) NOT NULL,
    English TINYINT UNSIGNED NOT NULL,
    Math TINYINT UNSIGNED NOT NULL,
    Computer TINYINT UNSIGNED NOT NULL
);

向Student表中插入两条记录的SQL语句如下:

insert into student values("zhangsan",69,86,77);
insert into student values("lisi",55,100,88);

(2)用SQL语句输出Student表中的所有记录;
输出Student表中的所有记录的SQL语句如下:

select * from student;

上述SQL语句执行后的结果截图如图所示。
在这里插入图片描述

(3)查询zhangsan的Computer成绩;
查询zhangsan的Computer成绩的SQL语句如下:

select name , Computer from student where name = "zhangsan";

上述语句执行后的结果截图如图所示。
在这里插入图片描述

(4)修改lisi的Math成绩,改为95。
修改lisi的Math成绩的SQL语句如下:

update student set Math=95 where name="lisi";

上述SQL语句执行结果截图如图所示。
在这里插入图片描述

2. 使用MySQL的JAVA客户端编程实现以下操作:

(1)向Student表中添加如下所示的一条记录:
在这里插入图片描述
向Student表添加上述记录的Java代码如下:

package com.xusheng.nosql.mysql;
import java.sql.*;
public class mysql_test {
    
    

    /**
     * @param xusheng
     */
    //JDBC DRIVER and DB
    static final String  DRIVER="com.mysql.jdbc.Driver";
    static final String DB="jdbc:mysql://localhost/student?useSSL=false";
    //Database auth
    static final String USER="root";
    static final String PASSWD="root";

    public static void main(String[] args) {
    
    
        // TODO Auto-generated method stub
        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) {
    
    
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (SQLException e) {
    
    
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
    
    
            if(stmt!=null)
                try {
    
    
                    stmt.close();
                } catch (SQLException e) {
    
    
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            if(conn!=null)
                try {
    
    
                    conn.close();
                } catch (SQLException e) {
    
    
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
    }
}

在这里插入图片描述
在这里插入图片描述

(2)获取scofield的English成绩信息
获取scofield的English成绩信息的Java代码如下:

package com.xusheng.nosql.mysql;
import java.sql.*;
public class mysql_qurty {
    
    

    /**
     * @param args
     */
    //JDBC DRIVER and DB
    static final String  DRIVER="com.mysql.jdbc.Driver";
    static final String DB="jdbc:mysql://localhost/student?useSSL=false";
    //Database auth
    static final String USER="root";
    static final String PASSWD="root";

    public static void main(String[] args) {
    
    
        // TODO Auto-generated method stub
        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) {
    
    
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (SQLException e) {
    
    
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
    
    
            if(rs!=null)
                try {
    
    
                    rs.close();
                } catch (SQLException e1) {
    
    
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            if(stmt!=null)
                try {
    
    
                    stmt.close();
                } catch (SQLException e) {
    
    
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            if(conn!=null)
                try {
    
    
                    conn.close();
                } catch (SQLException e) {
    
    
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
    }
}

在这里插入图片描述

(二)HBase数据库操作

学生表Student如表14-8所示。
在这里插入图片描述

1. 根据上面给出的学生表Student的信息,执行如下操作:

(1)用Hbase Shell命令创建学生表Student;
创建Student表的命令如下:

create 'student','score'

向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'

上述命令执行结果截图如图所示。
在这里插入图片描述

(2)用scan命令浏览Student表的相关信息;
用scan指令浏览Student表相关信息的命令如下:

scan 'student'

上述命令执行结果截图如图所示。
在这里插入图片描述
(3)查询zhangsan的Computer成绩;
查询zhangsan的Computer成绩的命令如下:

get 'student','zhangsan','score:Computer'

上述命令执行结果截图如图所示。
在这里插入图片描述

(4)修改lisi的Math成绩,改为95。
修改lisi的Math成绩的命令如下:

put 'student','lisi','score:Math','95'

上述命令的执行结果截图如图所示。
在这里插入图片描述

2. 用HBase API编程实现以下操作:

(1)添加数据:English:45 Math:89 Computer:100
在这里插入图片描述
实现添加数据的Java代码如下:

package com.xusheng.nosql.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 hbase_insert {
    
    

    /**
     * @param xusheng
     */
    public static Configuration configuration;
    public static Connection connection;
    public static Admin admin;
    public static void main(String[] args) {
    
    
        // TODO Auto-generated method stub
        configuration  = HBaseConfiguration.create();
        //configuration.set("hbase.rootdir","hdfs://localhost:9000/hbase");
        //configuration.set("hbase.rootdir","hdfs://hadoop102:8020/HBase");
        configuration.set("hbase.zookeeper.quorum","hadoop102,hadoop103,hadoop104");

        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) {
    
    
            // TODO Auto-generated catch block
            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();
        }
    }
}

执行完上述代码以后,可以用scan命令输出数据库数据,以检验是否插入成功,执行结果截图如图所示。
在这里插入图片描述

(2)获取scofield的English成绩信息。
Java代码如下:

package com.xusheng.nosql.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 hbase_query {
    
    

    /**
     * @param args
     */
    public static Configuration configuration;
    public static Connection connection;
    public static Admin admin;
    public static void main(String[] args) {
    
    
        // TODO Auto-generated method stub
        configuration  = HBaseConfiguration.create();
        //configuration.set("hbase.rootdir","hdfs://localhost:9000/hbase");
        //configuration.set("hbase.rootdir","hdfs://hadoop102:8020/HBase");
        configuration.set("hbase.zookeeper.quorum","hadoop102,hadoop103,hadoop104");

        try{
    
    
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        }catch (IOException e){
    
    
            e.printStackTrace();
        }
        try {
    
    
            getData("student","scofield","score","English");
        } catch (IOException e) {
    
    
            // TODO Auto-generated catch block
            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();
        }
    }
}

可以在IDEA中执行上述代码,会在控制台中输出如下信息:
在这里插入图片描述

(三)Redis数据库操作

Student键值对如下:

zhangsan:{
			English: 69
			Math: 86
			Computer: 77
}
lisi:{
			English: 55
			Math: 100
			Computer: 88

1. 根据上面给出的键值对,完成如下操作:

(1)用Redis的哈希结构设计出学生表Student(键值可以用student.zhangsan和student.lisi来表示两个键值属于同一个表);
插入上述键值对的命令如下:

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 

(2)用hgetall命令分别输出zhangsan和lisi的成绩信息;
查询zhangsan成绩信息的命令如下:

hgetall student.zhangsan

执行该命令的结果截图如图所示
在这里插入图片描述

查询lisi成绩信息的命令如下:

hgetall student.lisi

执行该命令的结果截图如图所示:
在这里插入图片描述

(3)用hget命令查询zhangsan的Computer成绩;
查询zhangsan的Computer成绩的命令如下:

hget student.zhangsan Computer

执行该命令的结果截图如所示:
在这里插入图片描述

(4)修改lisi的Math成绩,改为95。
修改lisi的Math成绩的命令如下:

hset student.lisi Math 95

执行该命令的结果截图如图所示:
在这里插入图片描述

2. 用Redis的JAVA客户端编程(jedis),实现如下操作:

(1)添加数据:English:45 Math:89 Computer:100
该数据对应的键值对形式如下:

scofield:{
			English: 45
			Math: 89
			Computer: 100

完成添加数据操作的Java代码如下:

package com.xusheng.nosql.redis;
import java.util.Map;
import redis.clients.jedis.Jedis;

public class jedis_test {
    
    

    /**
     * @param args
     */
    public static void main(String[] args) {
    
    
        // TODO Auto-generated method stub
        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());
        }
    }
}

在idea中执行程序时,在idea控制台输出的信息截图如图所示:
在这里插入图片描述

(2)获取scofield的English成绩信息
获取scofield的English成绩信息的Java代码如下:

package com.xusheng.nosql.redis;

import java.util.Map;
import redis.clients.jedis.Jedis;

public class jedis_query {
    
    

    /**
     * @param xusheng
     */
    public static void main(String[] args) {
    
    
        // TODO Auto-generated method stub
        Jedis jedis = new Jedis("localhost");
        String value=jedis.hget("student.scofield", "English");
        System.out.println("scofield's English score is:    "+value);
    }
}

在idea中执行上述代码后,在idea控制台输出的信息截图如图所示:
在这里插入图片描述

(四)MongoDB数据库操作

Student文档如下:

{
    
    
	“name”: “zhangsan”,
	“score”: {
    
    
				“English”: 69,
				“Math”: 86,
				“Computer”: 77
	}
}
{
    
    
	“name”: “lisi”,
	“score”: {
    
    
				“English”: 55,
				“Math”: 100,
				“Computer”: 88
	}
}

1. 根据上面给出的文档,完成如下操作:

(1)用MongoDB Shell设计出student集合;
首先,切换到student集合,命令如下:

use student

其次,定义包含上述两个文档的数组,命令如下:

var stus=[
{
    
    "name":"zhangsan","scores":{
    
    "English":69,"Math":86,"Computer":77}},                    {
    
    "name":"lisi","score":{
    
    "English":55,"Math":100,"Computer":88}} ]

最后,调用如下命令插入数据库:

db.student.insert(stus)

上述命令及其执行结果的截图如图所示:
在这里插入图片描述
(2)用find()方法输出两个学生的信息;
用find()方法输出两个学生信息的命令如下:

db.student.find().pretty()

上述命令及其执行结果的截图如图所示:
在这里插入图片描述

(3)用find()方法查询zhangsan的所有成绩(只显示score列);
用find函数查询zhangsan的所有成绩的命令如下:

db.student.find({
    
    "name":"zhangsan"},{
    
    "_id":0,"name":0})

上述命令及其执行结果的截图如图所示:
在这里插入图片描述

(4)修改lisi的Math成绩,改为95。
修改lisi的Math成绩的命令如下:

db.student.update({
    
    "name":"lisi"}, {
    
    "$set":{
    
    "score.Math":95}} )

上述命令及其执行结果的截图如图所示:
在这里插入图片描述

2. 用MongoDB的Java客户端编程,实现如下操作:

(1)添加数据:English:45 Math:89 Computer:100
与上述数据对应的文档形式如下:

{
    
    
		“name”: “scofield”,
		“score”: {
    
    
					“English”: 45,
					“Math”: 89,
					“Computer”: 100
		}
}

Java代码如下:

package com.xusheng.nosql.MongoDB;
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 mongo_insert {
    
    

    /**
     * @param args
     */
    public static void main(String[] args) {
    
    
        // TODO Auto-generated method stub
        //实例化一个mongo客户端
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        //实例化一个mongo数据库
        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("文档插入成功");
    }
}

在这里插入图片描述
可以使用find()方法验证数据是否已经成功插入到MongoDB数据库中,具体命令及其执行结果截图如图所示:
在这里插入图片描述

(2)获取scofield的所有成绩成绩信息(只显示score列)
Java代码如下:

package com.xusheng.nosql.MongoDB;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

public class mongo_query {
    
    


/**
     * @param args
     */

    public static void main(String[] args) {
    
    
        // TODO Auto-generated method stub
        //实例化一个mongo客户端
        MongoClient  mongoClient=new MongoClient("localhost",27017);
        //实例化一个mongo数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("student");
        //获取数据库中某个集合
        MongoCollection<Document> collection = mongoDatabase.getCollection("student");
        //进行数据查找,查询条件为name=scofield, 对获取的结果集只显示score这个域
        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());
    }
}

在这里插入图片描述

四、心得体会

HB ase 定义
HBase 是一种分布式、可扩展、支持海量数据存储的 NoSQL 数据库。
HBase 数据模型
逻辑上,HBase 的数据模型同关系型数据库很类似,数据存储在一张表中,有行有列。
但从 HBase 的底层物理存储结构(K-V)来看,HBase 更像是一个 multi-dimensional map。

猜你喜欢

转载自blog.csdn.net/m0_52435951/article/details/124896446