今天我們對之前講的三個(gè)數(shù)據(jù)庫自行創(chuàng)建一個(gè)類,并修改里面的增刪改查方法。
Python與MongoDB交互
安裝模塊:
pip install pymongo:安裝模塊pymongo
連接數(shù)據(jù)庫:
import pymongo # 導(dǎo)入pymongo
client = pymongo.MongoClient() # 連接MongoDB數(shù)據(jù)庫,會得到一個(gè)連接對象
db = client['student'] #指定數(shù)據(jù)庫
stu = db['stu'] # 指定集合
增刪改查:
stu.insert({'name':'moran','age':18})
stu.insert([{'name':'wanzi','age':20},{'name':'xiaobai','age':22}])
stu.update({'age':22},{'$set':{'age':24}}) # 改age等于22的年齡
'''
pip install pymongo/pymysql/redis -i https://pypi.douban.com/simple
'''
class MyMongoDB: # 所有類都繼承了object
'''初始化'''
def __init__(self,db,col): # 用戶傳入對應(yīng)的庫與集合進(jìn)行指定
import pymongo
self.client = pymongo.MongoClient() # 連接MongoDB數(shù)據(jù)庫,會得到一個(gè)連接對象
self.db = self.client[db] # 指定庫
self.col = self.db[col] #指定集合
'''重寫增方法'''
def insert(self,data,onlyOne=True):
if onlyOne:
self.col.insert_one(data)
else:
self.col.insert_many(data)
'''重寫查方法'''
def select(self,query=None,onlyOne=True): # 默認(rèn)查詢條件為空,默認(rèn)只查詢一條
if onlyOne:
res = self.col.find_one(query)
return list(res)
else:
res = self.col.find(query)
return list(res)
'''重寫改方法'''
def set(self,data,new_data,onlyOne=True):
if onlyOne:
self.col.update_one(data,{'$set':new_data})
else:
self.col.update_many(data,{'$set':new_data})
'''重寫刪方法'''
def delete(self,data,onlyOne=True):
if onlyOne:
self.col.delete_one(data)
else:
self.col.delete_many(data)
stu = MyMongoDB('student','stu')
# stu.insert({'name':'dust','age':58})
# stu.set({'age':58},{'age':28},onlyOne=False)
# stu.delete({'age':28})
# stu.delete({'age':18,'name':'moran'},onlyOne=False)
# stu.delete({'$or':[{'name':'xiaobai'},{'age':36}]},onlyOne=False)
# print(stu.select({'age':58})) # 也只查詢一條
# print(stu.select({'age':58},onlyOne=False)) # 查詢多條
print(stu.select(onlyOne=False))
"""mysql"""
import pymysql
db_config={
'host':'127.0.0.1',
'port':3306,
'user':'admin',
'password':'', #密碼輸自己的,這里隱藏了
'db':'mydb16',
'charset':'utf8'
}
connection = pymysql.connect(**db_config) # 連接MySQL數(shù)據(jù)庫,默認(rèn)開啟事務(wù)
cur = connection.cursor() # 生成游標(biāo)對象(SQL語句的執(zhí)行依賴于游標(biāo))
try:
# sql = 'insert into mr(name,idcard) values("beidou","556612"),("zilin","889945")'
# cur.execute(sql) # 執(zhí)行SQL語句
sql = 'delete from mr where id>3'
cur.execute(sql)
# sql = 'select * from mr'
# res = cur.execute(sql)
# print(res)
# print(cur.fetchone()) # 查詢單條數(shù)據(jù)
# print(cur.fetchmany(3)) # 查詢3條數(shù)據(jù)
# print(cur.fetchall()) # 查詢?nèi)繑?shù)據(jù)
except Exception as e:
connection.rollback()
print("發(fā)生了異常,正在進(jìn)行事務(wù)回滾")
else:
connection.commit() # 默認(rèn)開啟事務(wù),需要確認(rèn)提交
finally:
cur.close() # 關(guān)閉游標(biāo)
connection.close() # 關(guān)閉鏈接
"""連接redis"""
import redis
"""decode_responses=True是響應(yīng)的編碼格式,需要指定,如果不指定返回的是bytes二進(jìn)制字節(jié)類型的數(shù)據(jù),制定了以后返回的是str字符串類型"""
red = redis.Redis(db=1,decode_responses=True) # 默認(rèn)為0號庫,若是0,可以不寫db,這里是1號庫。
# red.set('num',111)
# red.lpush('myli',1,2,3,'a')
red.zadd('zse1',{'moran':100,'beidou':18})
# print(red.get('num')) # 獲取num數(shù)據(jù)的值
print(red.keys())
print(red.lrange('myli',0,-1)) # 查看列表從開頭到結(jié)尾的數(shù)據(jù)
print(red.zrange('zse1',0,-1,withscores=True))
文章到這里就結(jié)束了!希望大家能多多支持Python(系列)!六個(gè)月帶大家學(xué)會Python,私聊我,可以問關(guān)于本文章的問題!以后每天都會發(fā)布新的文章,喜歡的點(diǎn)點(diǎn)關(guān)注!一個(gè)陪伴你學(xué)習(xí)Python的新青年!不管多忙都會更新下去,一起加油!
Editor:Lonelyroots