#pymongo pymysql redis
#python操作mongodb
#封装在一个类里 class(def 函数,方法)
class Mymongo:
def __init__(self, database, collection): #进行指定连接
import pymongo
self.client = pymongo.MongoClient() #链接Momgodb
self.db = self.client[database] #指定库
self.col = self.db[collection] #指定集合
def insert(self, data, onlyOne=True):
if onlyOne:
self.col.insert_one(data)
else:
self.col.insert_many(data)
def find(self, query=None, onlyOne=True):
if onlyOne:
res = self.col.find_one(query)
return res
else:
res = self.col.find(query)
return list(res)
def update(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)
mr = Mymongo('stu', 'xiaohua')
#print(list(mr.col.find()))
#mr.insert({'name':'test','age':18})
#mr.insert([{'name': 'six', 'age': 16},{'name': 'seven', 'age': 17},{'name': 'eight', 'age': 18}], onlyOne=False)
#print(mr.find({'age': 18}, onlyOne=False))
#print(mr.find({'age': 18}))
#mr.update({'age': 28},{'age':38}, onlyOne=False)
mr.delete({'age': 38}, onlyOne=False)
print(mr.find(onlyOne=False))
import pymysql
db_config = {
'host': '127.0.0.1',
'port': 3306,
'user': 'admin',
'password': 'qwe123',
'db': 'zhang',
'charset': 'utf8'
} #配置信息
conn = pymysql.connect(**db_config) #产生与Mysql的链接
cur = conn.cursor() #获得游标对象,供sql语句执行使用
#sql = 'select * from mr;'
#sql = "insert into mr(name, age, phone) values('one', 11, '12345665432');"
#cur.execute(sql) #执行sql语句
try:
#sql = "insert into mr(name, age, phone) values('two', 12, '19345665432');"
sql = 'select * from mr;'
cur.execute(sql) #执行sql语句
#print(list(cur))
#print(cur.fetchone()) #获得单条
#print(cur.fetchmany(2)) #获取多条
print(cur.fetchall()) #获取全部数据
except Exception as e:
print(e)
conn.rollback() #事务回滚
else:
conn.commit() #事务提交
finally:
cur.close() #关闭游标
conn.close() #关闭链接
import redis
#redis.Redis(host='127.0.0.1', decode_responses=True)
red = redis.StrictRedis(host='127.0.0.1', decode_responses=True, db=0)
#decode_responses=True, 指定True返回的是str类型数据,否则返回的二进制字节数据
#red.set('num_11', 12345) #db不指定默认0号库
#print(red.get('num_11'))
#print(red.lrange('xx', 0, -1))
07-11
45万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
12-01
637
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)