MySQL學習筆記05(redis,mongoDB)
一、python遠端操作 redis
1.1 前提準備
1、安裝redis第三方庫
pip install redis
2、修改配置檔案
vim redis.conf
註釋掉/bind中:bind 127.0.0.1 (ip)
修改/protected:protected-mode no (關閉安全模式)
1、建立一個產品表 mysql -h localhost -u root -p use mydb; create table products( id int primary key auto_increment, name varchar(20) not null, price double not null ); #插入記錄 insert into products(name,price)values('洗衣粉',12.5),('旺旺雪餅',15),('辣條',5); #查看錶 select * from products; +----+--------------+-------+ | id | name | price | +----+--------------+-------+ | 1 | 洗衣粉 | 12.5 | | 2 | 旺旺雪餅 | 15 | | 3 | 辣條 | 5 | +----+--------------+-------+ 2、啟動redis
[email protected]:~$ redis-server redis.conf [email protected]:~$ redis-cli 127.0.0.1:6379>
1.2 python程式碼演示
# cache_tool.py import pymysql,redis def selectFromMySQL(_id): # 根據產品id從MySQL資料庫查詢產品 conn = pymysql.Connect( host='192.168.0.111:22',#虛擬機器地址 port=3306, user='root', password='rock1204', database='mydb', charset='utf8', ) cursor = conn.cursor() sql = "select id,name,price from products where id=%d" try: cursor.execute(sql%_id) product = cursor.fetchone() except Exception as e: print("操作MySQL查詢資料發生異常了:",e) finally: cursor.close() conn.close() return product def saveToRedis(product): # 將MySQL中查詢的產品儲存到Redis中 r = redis.Redis("192.168.0.111:22",6379) # 建立操作Redis的例項 r.hmset("product:"+str(product[0]),{'id':product[0],'name':product[1],'price':product[2]}) def selectFromRedis(_id): # 從Redis中查詢資料,並返回 r = redis.Redis("192.168.0.111:22", 6379) # 建立操作Redis的例項 product_dict = r.hgetall("product:"+str(_id)) # 以字典形式獲取,位元組序列 show_result = {} for k,v in product_dict.items(): show_result[k.decode()] = v.decode() # 解碼位元組序列 return show_result
#client.py from cache_tool import * _id = 1 print("先從Redis中查詢") data = selectFromRedis(_id) # 從Redis中查 print("從Redis中查詢的資料是:",data) if data: print("恭喜,Redis命中啦~~~") print("從Redis中查詢的資料是:",data) else: print("Redis中沒有,只能從MySQL中查詢了。。。。。。") product = selectFromMySQL(_id) if product: saveToRedis(product) print('已經將產品資訊儲存到Redis了') print("從MySQL中查詢的資訊是:",product) else: print("Sorry,系統暫無此資訊!!!")
二、mangoDB
檢視映象來源
vim /etc/apt/sources.list
vim /etc/apt/sources.list # deb cdrom:[Ubuntu 16.04.2 LTS _Xenial Xerus_ - Release amd64 (20170215.2)]/ xenial main restricted # See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to # newer versions of the distribution. deb http://mirrors.aliyun.com/ubuntu/ xenial main restricted # deb-src http://cn.archive.ubuntu.com/ubuntu/ xenial main restricted ## Major bug fix updates produced after the final release of the ## distribution. deb http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted # deb-src http://cn.archive.ubuntu.com/ubuntu/ xenial-updates main restricted ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team. Also, please note that software in universe WILL NOT receive any ## review or updates from the Ubuntu security team. deb http://mirrors.aliyun.com/ubuntu/ xenial universe # deb-src http://cn.archive.ubuntu.com/ubuntu/ xenial universe deb http://mirrors.aliyun.com/ubuntu/ xenial-updates universe # deb-src http://cn.archive.ubuntu.com/ubuntu/ xenial-updates universe ## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu ## team, and may not be under a free licence. Please satisfy yourself as to ## your rights to use the software. Also, please note that software in ## multiverse WILL NOT receive any review or updates from the Ubuntu ## security team. deb http://mirrors.aliyun.com/ubuntu/ xenial multiverse # deb-src http://cn.archive.ubuntu.com/ubuntu/ xenial multiverse "/etc/apt/sources.list" [只讀] 51L, 2885C
2.1 MongoDB簡介
MongoDB 是由C++語言編寫的,是一個基於分散式檔案儲存的開源資料庫管理系統
安裝方式:
sudo apt-get install mongodb
進入mongodb環境:mongo
資料庫(db)------>集合(collections)---->文件
2.2 MongoDB的操作
檢視所有資料庫 : show dbs
檢視當前資料庫: db
進入指定資料庫: use 資料庫名
顯示當前庫中所有的集合: show collections
建立一個集合: db.createCollection("集合名稱”)
向集合中插入文件:
db.集合稱.insert({name:'tom',age:20,score:65})
db.集合名稱.save(資料) # 若存在,則修改
查詢指定集合的所有資料
db.集合名稱.find()
db.集合名稱.find().pretty()
刪除集合
db.集合名.drop()
刪除當前資料庫
db.dropDatabase()
例一:查詢students集合中成績大於80分的文件
db.students.find({score:{$gt:80}})
例二:查詢students集合中成績大於80分且小於90分的文件
db.students.find({score:{lt:90}})
例三:從students集合中刪除名字為‘alice’的文 檔
db.students.remove({name:'alice'})
2.3 程式碼演示
[email protected]:~$ mongo #進入mongoDB
MongoDB shell version: 2.6.10
connecting to: test
> db #檢視當前資料庫
test
> show dbs #檢視所有資料庫
admin (empty)
local 0.078GB
> db #檢視當前資料庫
test
> use mydb #進入指定資料庫
switched to db mydb
> show collections #檢視所有集合
> db #檢視當前資料庫
mydb
> show dbs #檢視所有資料庫
admin (empty)
local 0.078GB
mydb (empty)
> db.createCollection('students') #建立students集合
{ "ok" : 1 }
> show collections #檢視所有集合
students
system.indexes
> db.students.insert({name:'tom',age:20,score:83.5}) #向students集合中插入文件
WriteResult({ "nInserted" : 1 })
> db.students.save({name:'jerry',age:28,score:63.5,sex:'man'}) #向students集合中插入文件,save:如果存在該文件則表示修改
WriteResult({ "nInserted" : 1 })
> db.students.find() #檢視資料庫所有文件
{ "_id" : ObjectId("5bb329c0a9f09b8ba5efd5f1"), "name" : "tom", "age" : 20, "score" : 83.5 }
{ "_id" : ObjectId("5bb32a86a9f09b8ba5efd5f2"), "name" : "jerry", "age" : 28, "score" : 63.5, "sex" : "man" }
> db.students.find().pretty() #檢視資料庫所有文件並格式化
{
"_id" : ObjectId("5bb329c0a9f09b8ba5efd5f1"),
"name" : "tom",
"age" : 20,
"score" : 83.5
}
{
"_id" : ObjectId("5bb32a86a9f09b8ba5efd5f2"),
"name" : "jerry",
"age" : 28,
"score" : 63.5,
"sex" : "man"
}
> db.students.find({score:{$gt:80}}) #查詢students集合中成績大於80分的文件
{ "_id" : ObjectId("5bb329c0a9f09b8ba5efd5f1"), "name" : "tom", "age" : 20, "score" : 83.5 }
> db.students.find({score:{$gt:60,$lt:80}}) 查詢students集合中成績大於60分且小於80分的文件
{ "_id" : ObjectId("5bb32a86a9f09b8ba5efd5f2"), "name" : "jerry", "age" : 28, "score" : 63.5, "sex" : "man" }
> db.students.remove({name:'jerry'}) #刪除文件
WriteResult({ "nRemoved" : 1 })
> db.students.save({name:'jerry',age:28,score:63.5,sex:'man'})
WriteResult({ "nInserted" : 1 })
> db.students.find().sort({score:1}) #升序排序
{ "_id" : ObjectId("5bb32e60a9f09b8ba5efd5f3"), "name" : "jerry", "age" : 28, "score" : 63.5, "sex" : "man" }
{ "_id" : ObjectId("5bb329c0a9f09b8ba5efd5f1"), "name" : "tom", "age" : 20, "score" : 83.5 }
> db.students.find().sort({score:-1}) #降序排序
{ "_id" : ObjectId("5bb329c0a9f09b8ba5efd5f1"), "name" : "tom", "age" : 20, "score" : 83.5 }
{ "_id" : ObjectId("5bb32e60a9f09b8ba5efd5f3"), "name" : "jerry", "age" : 28, "score" : 63.5, "sex" : "man" }
> db.students.drop() #刪除集合
true
> show dbs
admin (empty)
local 0.078GB
mydb 0.078GB
> db.dropDatabase() #刪除資料庫
{ "dropped" : "mydb", "ok" : 1 }
> show dbs
admin (empty)
local 0.078GB