大数据技术实验四

  • MySQL数据库操作

Student表如表A-4所示。

表A-4 学生表Student

Name

English

Math

Computer

zhangsan

69

86

77

lisi

55

100

88

  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语句执行后的结果截图如图A-1所示。

图A-1 结果截图(1)

(3)查询zhangsan的Computer成绩;

查询zhangsan的Computer成绩的SQL语句如下:

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

    上述语句执行后的结果截图如图A-2所示。

图A-2 结果截图(2)

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

        修改lisi的Math成绩的SQL语句如下:

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

        上述SQL语句执行结果截图如图A-3所示。

图A-3 结果截图(3)

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

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

scofield

45

89

100

向Student表添加上述记录的Java代码如下:

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="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代码如下:

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/test";

//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表如表A-5所示。

表A-5 学生表Student

     name

score

English

Math

Computer

zhangsan

69

86

77

lisi

55

100

88

根据上面给出的学生表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'

上述命令执行结果截图如图A-4所示。

图A-4 结果截图(4)

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

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

scan 'student'

上述命令执行结果截图如图A-5所示。

图A-5 结果截图(5)

(3)查询zhangsan的Computer成绩

查询zhangsan的Computer成绩的命令如下:

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

上述命令执行结果截图如图A-6所示。

图A-6 结果截图(6)

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

修改lisi的Math成绩的命令如下:

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

上述命令的执行结果截图如图A-7所示。

图A-7 结果截图(7)

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

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

scofield

45

89

100

实现添加数据的Java代码如下:

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

            }

        }

}

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

图A-8 结果截图(8)

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

Java代码如下:

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

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

            }

        }

}

可以在Eclipse中执行上述代码,会在控制台中输出如下信息:

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

执行该命令的结果截图如图A-9所示。

图A-9 结果截图(9)

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

hgetall student.lisi

执行该命令的结果截图如图A-10所示。

图A-10 结果截图(10)

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

查询zhangsan的Computer成绩的命令如下:

hget student.zhangsan Computer

执行该命令的结果截图如A-11所示。

图A-11 结果截图(11)

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

修改lisi的Math成绩的命令如下:

hset student.lisi Math 95

执行该命令的结果截图如图A-12所示。

图A-12 结果截图(12)

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

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

scofield:{

English: 45

Math: 89

Computer: 100

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

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

}

}

}

在Eclipse中执行程序时,需要添加JAR包jedis-2.9.0.jar,这个JAR包可以到教程官网的“下载专区”的“实验答案”目录中下载。在Eclipse中执行上述代码后,在Eclipse控制台输出的信息截图如图A-13所示。

图A-13 信息截图(1)

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

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

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

}

}

在Eclipse中执行上述代码后,在Eclipse控制台输出的信息截图如图A-14所示。

A-14 信息截图(2)

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

上述命令及其执行结果的截图如图A-15所示。

图A-15 结果截图(13)

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

用find()方法输出两个学生信息的命令如下:

db.student.find().pretty()

上述命令及其执行结果的截图如图A-16所示。

图A-16 结果截图(14)

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

用find函数查询zhangsan的所有成绩的命令如下:

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

    上述命令及其执行结果的截图如图A-17所示。

图A-17 结果截图(15)

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

修改lisi的Math成绩的命令如下:

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

    上述命令及其执行结果的截图如图A-18所示。

图A-18 结果截图(16)

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

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

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

{

“name”: “scofield”,

“score”: {

“English”: 45,

“Math”: 89,

“Computer”: 100

}

}

    实现上述添加数据操作的Java代码如下:

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数据库中,具体命令及其执行结果截图如图A-19所示。

图A-19 结果截图(17)

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

Java代码如下:

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

}

}

  • 18
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值