12.17

实验4

NoSQL和关系数据库的操作比较

 

1.实验目的

1)理解四种数据库(MySQL、HBase、Redis和MongoDB)的概念以及不同点

2)熟练使用四种数据库操作常用的Shell命令;

3)熟悉四种数据库操作常用的Java API

2.实验平台

1操作系统:Linux(建议Ubuntu16.04Ubuntu18.04);

2Hadoop版本:3.1.3

3MySQL版本:5.6;

4HBase版本:2.2.2

5Redis版本5.0.5

6MongoDB版本4.0.16

7JDK版本:1.8

8Java IDEEclipse;

3.实验步骤

(一) MySQL数据库操作

学生表如14-7所示。

14-7 学生表Student

Name

English

Math

Computer

zhangsan

69

86

77

lisi

55

100

88

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

(1)在MySQL中创建Student表,并录入数据;

命令:

创建表:

CREATE TABLE Student

 ( Name VARCHAR(50) NOT NULL, English INT NOT NULL, Math INT NOT NULL, Computer INT NOT NULL );

新增数据:

INSERT INTO Student (Name, English, Math, Computer) VALUES ('zhangsan', 69, 86, 77), ('lisi', 55, 100, 88);

结果:

创建表:

 

 

新增数据:

 

 

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

命令:SELECT * FROM Student;

结果:

 

 

(3)查询zhangsanComputer成绩

命令:select computer from student where name='zhangsan';

结果:

 

 

4修改lisiMath成绩改为95。

命令:update student set math=95 where name='lisi';

结果:

 

 

 

2.根据上面已经设计出的Student,使用MySQLJAVA客户端编程实现以下操作:

1)向Student表中添加如下所示的一条记录:

scofield

45

89

100

package org.example.si;

import java.sql.*;

public class mysql_test {
    /**
     * @param args
     */
//JDBC DRIVER and DB
    static final String DRIVER = "com.mysql.jdbc.Driver";
    static final String DB = "jdbc:mysql://localhost/test";
    //Database auth
    static final String USER = "root";
    static final String PASSWD = "123456789";

    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获取scofieldEnglish成绩信息

package com.four;

import java.sql.*;

public class MySQLStudentOperations {
    // 数据库连接信息
    private static final String URL = "jdbc:mysql://localhost:3306/bigdata";
    private static final String USER = "root";
    private static final String PASSWORD = "123456789";

    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 1. 连接数据库
            connection = DriverManager.getConnection(URL, USER, PASSWORD);

            // 2. 插入 scofield 的记录
            String insertSQL = "INSERT INTO Student (Name, English, Math, Computer) VALUES (?, ?, ?, ?)";
            preparedStatement = connection.prepareStatement(insertSQL);
            preparedStatement.setString(1, "scofield");
            preparedStatement.setInt(2, 45);
            preparedStatement.setInt(3, 89);
            preparedStatement.setInt(4, 100);
            int rowsInserted = preparedStatement.executeUpdate();
            System.out.println("插入记录成功,受影响的行数: " + rowsInserted);

            // 3. 获取 scofield  English 成绩
            String querySQL = "SELECT English FROM Student WHERE Name = ?";
            preparedStatement = connection.prepareStatement(querySQL);
            preparedStatement.setString(1, "scofield");
            resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                int englishScore = resultSet.getInt("English");
                System.out.println("scofield 的 English 成绩是: " + englishScore);
            } else {
                System.out.println("未找到 scofield 的记录");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭资源
                if (resultSet != null) resultSet.close();
                if (preparedStatement != null) preparedStatement.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

 

结果:

 

 

(二)HBase数据库操作

学生表Student如表14-8所示。

14-8 学生表Student

     name

score

English

Math

Computer

zhangsan

69

86

77

lisi

55

100

88

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

(1)Hbase Shell命令创建学生Student

命令:

create 'Student1', 'score'

结果

 

 

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

命令:

scan Student

结果:

 

 

(3)查询zhangsan的Computer成绩

命令:get 'Student1', 'zhangsan', 'score:Computer'

结果:

 

 

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

命令:put 'Student', 'lisi', 'score:Math', '95'

结果:

 

 

2.根据上面已经设计出的Student表用HBase API编程实现以下操作:

1)添加数据:English:45  Math:89 Computer:100

scofield

45

89

100

package org.example.si;

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 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");
        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();
        }
    }
}

 

 

2获取scofieldEnglish成绩信息

package com.four;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class HBaseStudentTable {
    public static void main(String[] args) throws IOException {
        // 配置 HBase 连接
        org.apache.hadoop.conf.Configuration config = HBaseConfiguration.create();
        config.set("hbase.zookeeper.quorum", "master"); // 替换为 Zookeeper 的主机名或 IP
        config.set("hbase.zookeeper.property.clientPort", "2181");

        // 创建连接和表实例
        try (Connection connection = ConnectionFactory.createConnection(config);
             Table table = connection.getTable(TableName.valueOf("Student1"))) {

            // (1) 添加数据
            String rowKey = "scofield";
            Put put = new Put(Bytes.toBytes(rowKey));
            put.addColumn(Bytes.toBytes("score"), Bytes.toBytes("English"), Bytes.toBytes("45"));
            put.addColumn(Bytes.toBytes("score"), Bytes.toBytes("Math"), Bytes.toBytes("89"));
            put.addColumn(Bytes.toBytes("score"), Bytes.toBytes("Computer"), Bytes.toBytes("100"));

            table.put(put); // 插入数据
            System.out.println("成功插入 scofield 的记录。");

            // (2) 获取 scofield  English 成绩
            Get get = new Get(Bytes.toBytes(rowKey));
            get.addColumn(Bytes.toBytes("score"), Bytes.toBytes("English"));
            Result result = table.get(get);

            byte[] value = result.getValue(Bytes.toBytes("score"), Bytes.toBytes("English"));
            if (value != null) {
                System.out.println("scofield 的 English 成绩是: " + Bytes.toString(value));
            } else {
                System.out.println("未找到 scofield 的 English 成绩。");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

运行结果:

 

 

 

(三)Redis数据库操作

Student键值对如下:

zhangsan:

English: 69

Math: 86

Computer: 77

lisi:

English: 55

Math: 100

Computer: 88

 

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

1Redis的哈希结构设计出学生表Student键值可以用student.zhangsan和student.lisi来表示两个键值属于同一个表);

插入上述键值对命令为:

127.0.0.1:6379> hset student.zhangsan English 69

(integer) 1

127.0.0.1:6379> hset student.zhangsan Math 86

(integer) 1

127.0.0.1:6379> hset student.zhangsan Computer 77

(integer) 1

127.0.0.1:6379> hset student.lisi English 55

(integer) 1

127.0.0.1:6379> hset student.lisi Math 100

(integer) 1

127.0.0.1:6379> hset student.lisi Computer 88

(integer) 1

  

(2)hgetall命令分别输出zhangsanlisi的成绩信息

查询 zhangsan lisi 成绩信息命令为:

hgetall student.zhangsan

 

 

hgetall student.lisi

 

 

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

命令为: hget student.zhangsan Computer

 

 

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

命令为:hset student.lisi Math 95

    

 

 

2.根据上面已经设计出的学生表Student,RedisJAVA客户端编程(jedis),实现如下操作:

1)添加数据:English:45  Math:89 Computer:100

该数据对应的键值对形式如下:

scofield:

English: 45

Math: 89

Computer: 100

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());

}

}

}

 

 

2获取scofieldEnglish成绩信息

import java.util.Map;

import redis.clients.jedis.Jedis;

public class jedis_query {

/** * @param args

*/

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);

}

}

 

 

(四)MongoDB数据库操作

Student文档如下:

{

“name”: “zhangsan”,

“score”: {

“English”: 69,

“Math”: 86,

“Computer”: 77

}

}

{

“name”: “lisi”,

“score”: {

“English”: 55,

“Math”: 100,

“Computer”: 88

}

}

 

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

1MongoDB Shell设计出student集合

 

 

 

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

 

 

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

 

 

4)修改lisi的Math成绩,95

 

 

2.根据上面已经设计出的Student集合,用MongoDBJava客户端编程,实现如下操作:

1添加数据:English:45 Math:89  Computer:100

与上述数据对应的文档形式如下:

{

“name”: “scofield”,

“score”: {

“English”: 45,

“Math”: 89,

“Computer”: 100

}

}

   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("文档插入成功");

}

通过以下截图,可以检测数据已经正确插入 MongoDB 数据库中

 

 

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

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.MongoCursor;

import com.mongodb.client.MongoDatabase;

import com.mongodb.client.model.Filters;

import static com.mongodb.client.model.Filters.eq;

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());

}

}

Eclipse 控制台可以输出查询得到的信息,红色区域为日志,可忽略

 

 

4.实验报告

题目:

比较NoSQL和关系数据库操作

姓名

陈庆振

日期 11.25

  • 实验环境:操作系统:Linux
  • Hadoop版本:2.7.3
  • MySQL版本:5.6
  • HBase版本:2.2.2
  • Redis版本:5.0.5
  • MongoDB版本:4.0.16
  • JDK版本:1.8
  • Java IDE:Eclipse

实验内容与完成情况:

MySQL操作:

创建和操作MySQL数据库中的Student表,包括建表、数据插入、查询和更新操作。

使用Java API执行数据库操作,如添加记录和查询特定学生成绩。

HBase操作:

通过HBase Shell创建和管理Student表,执行数据浏览、查询和更新操作。

使用HBase Java API进行数据添加和查询操作。

Redis操作:

利用Redis的哈希数据结构管理Student表,执行数据插入、查询和更新操作。

通过Jedis Java客户端库实现数据的添加和查询。

MongoDB操作:

MongoDB中创建和操作student集合,执行文档的插入、查询和更新操作。

使用MongoDB Java客户端进行文档的添加和查询操作。

出现的问题:在配置HBase时,遇到了Zookeeper连接问题,原因是Zookeeper的配置信息不正确。

在使用Redis时,遇到了Jedis连接超时的问题,原因是网络配置不当。

解决方案(列出遇到的问题和解决办法,列出没有解决的问题):对于HBase的Zookeeper连接问题,检查并更新了Zookeeper的配置信息,确保了正确的主机名和端口号。

对于Redis的Jedis连接超时问题,检查了网络配置,并确保了Redis服务器的可访问性。

posted @ 2024-12-18 18:20  七安。  阅读(8)  评论(0编辑  收藏  举报