如果对你有帮助,点个赞吧
实验四:NoSQL和关系数据库的操作比较
一、实验目的
 理解四种数据库(MySQL、HBase、Redis和MongoDB)的概念以及不同点;
 熟练使用四种数据库操作常用的Shell命令;
 熟悉四种数据库操作常用的Java API。
二、实验平台
 操作系统:Linux(Ubuntu18.04);
 Hadoop版本:3.1.3;
 MySQL版本:Ver14.14 Distrib 5.7.32-0ubuntu0.18.04.1;
 HBase版本:2.2.1;
 Redis版本:6.0.9;
 MongoDB版本:3.6.3;
 JDK版本:openjdk-1.8;
 Java IDE:Eclipse;
三、实验步骤
(一) MySQL数据库操作

提前创建好bigdata数据库

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql

学生表Student
Name English Math Computer
zhangsan 69 86 77
lisi 55 100 88

  1. 根据上面给出的Student表,在MySQL数据库中完成如下操作:
    (1) 在MySQL中创建Student表,并录入数据;
    首先创建表:
    create table student(
    name varchar(30) not null,
    English tinyint unsigned not null,
    Math tinyint unsigned not null,
    Computer tinyint unsigned not null
    );

    可见表已创建成功,此时开始添加数据:
    insert into student values(“zhangsan”,69,86,77);
    insert into student values(“lisi”,55,100,88);

    (2) 用SQL语句输出Student表中的所有记录;
    SQL语句:select * from student;

    (3) 查询zhangsan的Computer成绩;
    SQL语句:select name , Computer from student where name = “zhangsan”;

    (4)修改lisi的Math成绩,改为95。
    SQL语句:update student set Math=95 where name=“lisi”;

    可见lisi的Math成绩已成功修改为95
    2.根据上面已经设计出的Student表,使用MySQL的JAVA客户端编程实现以下操作:
    (1)向Student表中添加如下所示的一条记录:
    scofield 45 89 100

新建一个项目mysqltest,然后再建mysql包,在包中新建java类Test1

mysql数据库gbk MySQL数据库与NoSQL数据库实验_数据库_02

去菜鸟教程中:https://www.runoob.com/java/java-mysql-connect.html 下载mysql的jar包并导入:

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mongodb_03


JAVA代码:

package mysqltest;
import java.sql.*;
public class Test1 {
	static final String DRIVER = "com.mysql.cj.jdbc.Driver";  
	static final String DB = "jdbc:mysql://localhost:3306/bigdata?serverTimezone=UTC"; // 数据库
	static final String USER = "root";
	static final String PASSWD = "123456";  
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		try { // 加载驱动程序
			Class.forName(DRIVER);
			System.out.println("正在连接数据库..."); // 打开一个连接
			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("插入成功");
		} 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();
				}
		}
	}
}

运行成功

mysql数据库gbk MySQL数据库与NoSQL数据库实验_数据库_04


在mysql中验证结果,如图数据成功添加:

mysql数据库gbk MySQL数据库与NoSQL数据库实验_数据库_05


(2)获取scofield的English成绩信息

新建java文件Test2

JAVA代码:

package mysqltest;
import java.sql.*;
public class Test2 {
	static final String DRIVER = "com.mysql.cj.jdbc.Driver";  
	static final String DB = "jdbc:mysql://localhost:3306/bigdata?serverTimezone=UTC"; // 数据库
	static final String USER = "root";
	static final String PASSWD = "123456"; 
	public static void main(String[] args) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try { // 加载驱动程序
			Class.forName(DRIVER);
			System.out.println("正在连接数据库..."); // 打开一个连接
			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" + "      " + "English");
			while (rs.next()) {
				System.out.printf("%-10s%-10d",rs.getString(1),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();
				}
		}
	}
}

运行成功,获取到scofield的English成绩信息:

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mongodb_06


(二)HBase数据库操作

学生表Student

name score

English Math Computer

zhangsan 69 86 77

lisi 55 100 88

  1. 根据上面给出的学生表Student的信息,执行如下操作:
    (1)用Hbase Shell命令创建学生表Student;
    进入hbase-2.2.2路径下,输入命令./bin/hbase shell

    创建 student3 表,create第一个参数位表名,后面为列/列族名

    插入数据

    (2)用scan命令浏览student3表的相关信息;

    (3)查询zhangsan的Computer成绩;

    (4)修改lisi的Math成绩,改为95。
    先修改,再用get命令验证结果

    2.根据上面已经设计出的student3表,用HBase API编程实现以下操作:
    (1)添加数据:English:45 Math:89 Computer:100
    scofield 45 89 100
    代码:
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 Test6 {
	public static Configuration configuration;
	public static Connection connection;
	public static Admin admin;
	public static void main(String[] args) {
		try {
			insertRow("student3", "scofield", "score", "English", "45");
			insertRow("student3", "scofield", "score", "Math", "89");
			insertRow("student3", "scofield", "score", "Computer", "100");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void insertRow(String tableName, String key, String colFamily, String col, String val)
			throws IOException {
		init();
		Table table = connection.getTable(TableName.valueOf(tableName));
		Put put = new Put(key.getBytes());
		put.addColumn(colFamily.getBytes(), col.getBytes(), val.getBytes());
		table.put(put);
		System.out.println("插入成功");
		table.close();
	close();
	}
	public static void init(){
	configuration  = HBaseConfiguration.create();
	configuration.set("hbase.rootdir","hdfs://localhost:9000/hbase");
	try{
	connection = ConnectionFactory.createConnection(configuration);
	admin = connection.getAdmin();
	    }catch (IOException e){
	e.printStackTrace();
	    }
	}
	public static void close() {
		try {
			if (admin != null) {
				admin.close();
			}
			if (null != connection) {
				connection.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

运行结果

mysql数据库gbk MySQL数据库与NoSQL数据库实验_redis_07


hbase shell查看

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql数据库gbk_08


(2)获取scofield的English成绩信息。

代码:

package bigdata_test4;
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.*;

public class Test7 {
	public static Configuration configuration;
	public static Connection connection;
	public static Admin admin;

	public static void main(String[] args) {
		try {
			getData("student3", "scofield", "score", "English");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void getData(String tableName, String rowKey, String colFamily, String col) throws IOException {
		init();
		Table table = connection.getTable(TableName.valueOf(tableName));
		Get get = new Get(rowKey.getBytes());
		get.addColumn(colFamily.getBytes(), col.getBytes());
		Result result = table.get(get);
		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)) + " ");
		}
		table.close();
		close();
	}

	public static void init() {
		configuration = HBaseConfiguration.create();
		configuration.set("hbase.rootdir", "hdfs://localhost:9000/hbase");
		try {
			connection = ConnectionFactory.createConnection(configuration);
			admin = connection.getAdmin();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

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

运行结果

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql_09


(三)Redis数据库操作

开启Redis服务器

mysql数据库gbk MySQL数据库与NoSQL数据库实验_数据库_10


新打开一个终端作为客户端

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql数据库gbk_11


Student键值对如下:

zhangsan:{

English: 69

Math: 86

Computer: 77


lisi:{

English: 55

Math: 100

Computer: 88


  1. 根据上面给出的键值对,完成如下操作:
    (1)用Redis的哈希结构设计出学生表Student(键值可以用student.zhangsan和student.lisi来表示两个键值属于同一个表);

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

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

    (4)修改lisi的Math成绩,改为95。
    hset命令修改
    hget查询lisi的数学成绩来验证结果

    2.根据上面已经设计出的学生表Student,用Redis的JAVA客户端编程(jedis),实现如下操作:
    (1)添加数据:English:45 Math:89 Computer:100
    该数据对应的键值对形式如下:
    scofield:{
    English: 45
    Math: 89
    Computer: 100

    新建一个项目redistest,新建java类Test

    JAVA代码:
package redistest;
import java.util.Map;
import redis.clients.jedis.*;

public class Test {
	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");
		System.out.println("信息添加成功:");
		System.out.println("student.scofield:");
		for (Map.Entry<String, String>entry : value.entrySet()) {//遍历
			//Map.Entry是Map中的一个接口,
			//表示一个一个映射项,有key,value
			System.out.println(entry.getKey() + ":" + entry.getValue());
		}
	}
}

运行成功:

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql数据库gbk_12


在shell中验证结果:hgetall student.scofield

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql_13


(2)获取scofield的English成绩信息

新建java文件Test2

JAVA代码:

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

运行成功,获取到scofield的English成绩信息:

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql数据库gbk_14


(四)MongoDB数据库操作

mysql数据库gbk MySQL数据库与NoSQL数据库实验_redis_15


启动和关闭mongodb命令如下:

1.	sudo service mongodb start
2.	sudo service mongodb stop

输入mongo进入shell

mysql数据库gbk MySQL数据库与NoSQL数据库实验_数据库_16


show dbs 显示当前所有的数据,现在没有数据内容

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql数据库gbk_17


接下来就可以开始做实验题目了

Student文档如下:

{

“name”: “zhangsan”,

“score”: {

“English”: 69,

“Math”: 86,

“Computer”: 77

}

}

{

“name”: “lisi”,

“score”: {

“English”: 55,

“Math”: 100,

“Computer”: 88

}

}

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

(1)用MongoDB Shell设计出student集合;

首先输入命令:use student 创建数据库名字, student就是数据库名字

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql数据库gbk_18


输入给出的Student文档中的数据

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql_19


最后输入命令db.student.insert(stus) 将以上数据插入student数据库

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql_20


(2)用find()方法输出两个学生的信息;

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mongodb_21


(3)用find()方法查询zhangsan的所有成绩(只显示score列);

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql数据库gbk_22


(4)修改lisi的Math成绩,改为95。

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

然后,再输入命令db.student.find().pretty() 来查看lisi的Math成绩是否成功修改为95

mysql数据库gbk MySQL数据库与NoSQL数据库实验_redis_23


可见,命令执行成功,成功将lisi的数学成绩修改为95

2.根据上面已经设计出的Student集合,用MongoDB的Java客户端编程,实现如下操作:
(1)添加数据:English:45 Math:89 Computer:100
与上述数据对应的文档形式如下:
{
“name”: “scofield”,
“score”: {
“English”: 45,
“Math”: 89,
“Computer”: 100
}
}

新建一个项目mongotest,新建java类Test1

JAVA代码:

import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.*;

public class Test1 {
	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("插入成功");
	}
}

运行结果:

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql_24


在shell中验证结果

mysql数据库gbk MySQL数据库与NoSQL数据库实验_mysql_25


(2)获取scofield的所有成绩信息(只显示score列)

新建java文件Test2

JAVA代码:

package mongotest;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.*;

public class Test2 {
	public static void main(String[] args) {
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		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();
		System.out.println("查询成功,如下:");
		while (cursor.hasNext())
			System.out.println(cursor.next().toJson());//格式化为 JSON 数据格式
	}
}

运行结果:

mysql数据库gbk MySQL数据库与NoSQL数据库实验_数据库_26


总结

本次实验四类数据库的安装运行均在linux中完成,深谙linux指令安装的方便快捷。这次实验相对于前几次实验较为简单,也几乎没有出错。对关系型数据库和非关系型数据库的区别有进一步的理解,非关系型数据库是一种数据结构化存储方法的集合,可以是文档或者键值对等。博客:

数据库名称 简介
1.MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品。MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MySQL RDBMS (Relational Database Management System,关系数据库管理系统) 应用软件之一。
2.Redis(全称:Remote Dictionary Server 远程字典服务)是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value 非关系型数据库,并提供多种语言的API。从2010年3月15日起,Redis的开发工作由VMware主持。从2013年5月开始,Redis的开发由Pivotal赞助。
3.MongoDB是一个基于分布式文件存储 [1] 的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。
MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。