NoSQL實驗


承接上一篇,HBase實驗,下一篇,MapReduce實驗

一 MySQL數據庫操作

安裝

參考廈大數據庫實驗室博客
一般安裝好Ubuntu后,第一次登錄時無法登錄,可以去更新root用戶的密碼,網上的很多教程我都試過了,總體來講可以分為兩步

  • 登錄mysql,網上的兩種方法都是可行的。
    一是終止服務,打開終端,輸入mysqld --skip-grant-tables,然后新建終端直接輸入mysql登錄,然后按照下面鏈接的方法修改密碼
    二是找到/etc/mysql/debian.cnf,利用里面的用戶和密碼登錄,然后修改密碼
  • 修改密碼
    就是三條語句,網上的一些教程只有一條語句,沒有刷新是不對的。
    解決MySql忘記root密碼和修改密碼的問題

Student學生表

Name English Math Computer
zhangsan 69 86 77
lisi 55 100 88

1. 根據上面給出的表格,利用MySQL5.6設計出student學生表格;

create table Student ( Name varchar(10), English int, Math int, Computer int);
insert Student values("zhansan",69,86,77);
insert Student values("lisi",55,100,88);

a) 設計完后,用select語句輸出所有的相關信息,並給出截圖;

select * from Student;


b) 查詢zhangsan的Computer成績,並給出截圖;

select Computer from Student where Name="zhansan";


c) 修改lisi的Math成績,改為95.給出截圖.

update Student set Math=95 where name="lisi"

2.根據上面已經設計出的student表,用MySQL的JAVA客戶端編程;

a) 添加數據:English:45 Math:89 Computer:100

scofield 45 89 100

b) 獲取scofield的English成績信息
要將驅動程序放入項目的BuildPath中,然后在編程中建立與數據庫的連接,接着執行事務,最后關閉返回的結果集、事務和連接。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Prac {
   static final String DRIVER = "com.mysql.jdbc.Driver";
   static final String DB = "jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf-8";
   
   static final String USER = "root";
   static final String PASSWD = "root";

   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 sql1 = "select name,English from Student where name='scofiled'";
   		String sql2 = "insert Student values('scofiled',45,89,100)";
   		stmt.executeUpdate(sql2);
   		//獲得結果集
   		rs = stmt.executeQuery(sql1);
   		System.out.println("Name\tEnglish");
   		while(rs.next()) 
   			System.out.println(rs.getString(1)+"\t"+rs.getInt(2));
   	}catch(Exception e) {
   		e.printStackTrace();
   	}finally{
   		try {
   			if(rs!=null)
   				rs.close();
   			if(stmt!=null)
   				stmt.close();
   			if(conn!=null)
   				conn.close();
   			} catch (SQLException e) {
   				e.printStackTrace();
   			}
   		System.out.println("執行完成");
   		}
   	}
}

二 HBase數據庫操作

安裝

見上一篇博客(本篇置頂有鏈接
Student學生表

1.根據上面給出的表格,用Hbase Shell模式設計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)設計完后,用scan指令瀏覽表的相關信息,給出截圖。

scan 'Student'


b)查詢zhangsan 的Computer成績,給出截圖。

get 'Student','zhangsan','score','Computer'


c)修改lisi的Math成績,改為95,給出截圖。

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

2.根據上面已經設計出的student,用Hbase API編程。

a)添加數據:English:45 Math:89 Computer:100

scofield 45 89 100

b)獲取scofield的English成績信息

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 PracNoSQL {
	private static Configuration conf;
	private static Connection conn;
	private static Admin admin;
	public static void main(String[] args) throws IOException {
		//init
		conf = HBaseConfiguration.create();
		
		try {
			conf.set("hbase.roodir", "hdfs://localhost:9000/hbase");
			conn = ConnectionFactory.createConnection(conf);
			admin = conn.getAdmin();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		TableName tableName = TableName.valueOf("Student");
		if(!admin.tableExists(tableName)) {
			System.out.println("該表不存在");
			System.exit(1);
		}
		Table table = conn.getTable(tableName);
		System.out.print("開始添加數據....");
		String[] course = {"English","Math","Computer"};
		int[] grade = {45,89,100};
		for(int i=0;i<3;i++) 
		{
			Put put = new Put("scofield".getBytes());
			put.add("score".getBytes(), course[i].getBytes(), String.valueOf(grade[i]).getBytes());
			table.put(put);
		}
		System.out.println("添加成功");
		
		System.out.print("獲取數據中....");
		Get get = new Get("scofield".getBytes());
		get.addColumn("score".getBytes(), "English".getBytes());
		Result res = table.get(get);
		System.out.println("成功");
		Cell[] cells = res.rawCells();
		for(Cell cell:cells)
			System.out.println("RowKey:"+new String(CellUtil.cloneRow(cell))+"\t"
					+"colFamily:"+new String(CellUtil.cloneFamily(cell))+"\t"
					+"col:"+new String(CellUtil.cloneQualifier(cell))+"\t"
					+"value:"+new String(CellUtil.cloneValue(cell)));
		
		//close
		try {
			if(admin!=null)
				admin.close();
			if(conn!=null)
				conn.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}

三 Redis數據庫操作

安裝

參考廈大數據庫實驗室博客

Student 鍵值對:
zhangsan:{

English: 69

Math: 86

Computer: 77

lisi:{

English: 55

Math: 100

Computer: 88

1. 根據上面給出的鍵值對,用Redis的哈希結構設計出上述表格;(鍵值可以用student.zhangsan,student.lisi來表示兩個鍵值屬於同一個表格)

HMSET student.zhangsan English 69 Math 86 Computer 77
HMSET student.lisi English 55 Math 100 Computer 88

a) 設計完之后,用hgetall命令分別輸出zhangsan和lisi的成績信息,並截圖;

HGETALL student.zhangsan
HGETALL student.lisi


b) 用hget命令查詢zhangsan 的Computer成績,給出截圖。

Hget student.zhangsan Computer


c) 修改lisi的Math成績,改為95,給出截圖。

HSET student.lisi Math 95 

2. 根據上面已經設計出的student表格,用Redis的JAVA客戶端編程(jedis)

a ) 添加數據:
scofield:{

English: 45

Math: 89

Computer: 100


b) 獲取scofield的English成績信息
redis有比較多的java客戶端,這里選擇的是jedis。在使用的時候要先下載jedis的最新版本並且導入到java項目的BuildPath里面去。

import redis.clients.jedis.Jedis;

public class prac {

   public static void main(String[] args) {
   	Jedis jedis = new Jedis("localhost");
   	System.out.print("開始插入數據.....");
   	
   	jedis.hset("student.scofield", "English","45");
   	jedis.hset("student.scofield", "Math","89");
   	jedis.hset("student.scofield", "Computer","100");
   	
   	System.out.println("DONE");
   	System.out.println("查詢數據....");
   	String value = jedis.hget("student.scofield", "English");
   	System.out.println("scofield:English  : "+value);
   }

}


四 MongoDB數據庫操作

安裝

參考廈大數據庫實驗室博客
我采用的是離線安裝的模式,所以啟動和結束與在線安裝是不同的。
Student文檔如下:
{

“name”: “zhangsan”,

“score”: {

“English”: 69,

“Math”: 86,

“Computer”: 77

}

}

{

“name”: “lisi”,

“score”: {

“English”: 55,

“Math”: 100,

“Computer”: 88

}

}

1. 根據上面給出的文檔,用Mongo shell設計出student集合.

use School
db.createCollection('student')
db.student.insert({name:'zhangsan',score:{English:69,Math:86,Computer:77}})
db.student.insert({name:'lisi',score:{English:55,Math:100,Computer:88}})

a) 設計完后,用find()方法輸出兩個學生的信息,給出截圖;

db.student.find()
db.student.find().pretty()


b) 用find函數查詢zhangsan 的所有成績(只顯示score列),給出截圖。

db.student.find({name:'zhangsan'},{'score':1})


c) 修改lisi的Math成績,改為95,給出截圖。

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

2. 根據上面已經設計出的student集合,用MongoDB的JAVA客戶端編程

a) 添加數據:English:45 Math:89 Computer:100

{

“name”: “scofield”,

“score”: {

“English”: 45,

“Math”: 89,

“Computer”: 100

}

}

b) 獲取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;

public class TestMongoDB {

    public static void main(String[] args) {
        MongoCollection<Document> collection = getCollection("School","student");
        insert(collection);
        find(collection);
    }
    
    public static MongoCollection<Document> getCollection(String dbname,String collectionname){
        MongoClient  mongoClient=new MongoClient("localhost",27017);
        MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname);
        MongoCollection<Document> collection = mongoDatabase.getCollection(collectionname);
        return collection;
    }
    public static void insert(MongoCollection<Document> collection){
        try{
            Document doc=new Document("name","scofield").append("score", new Document("English",45).append("Math",89).append("Computer",100));
            collection.insertMan(doc);  
            System.out.println("插入成功"); 
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }
    public static void find(MongoCollection<Document> collection){
        try{
            MongoCursor<Document>  cursor= collection.find(new Document("name","scofield")).projection(new Document("score",1)).iterator();
            while(cursor.hasNext()){
                System.out.println(cursor.next().toJson());
            }
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }
}

總結

  • 多種數據庫都只是粗淺地學習了一下,讓自己覺得非常不舒服,希望能有時間做出項目,並在項目中學習各種數據庫的使用。
  • NoSQL 數據庫否定了One Fits All,帶來了很多新的數據庫類型。

人生此處,絕對樂觀


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM