已知有三个数据库mysql,mongodb和redis,已经分别存储了不同的学生信息,数据全部采用字符串类型,只有id和name两个字段(在mongo和redis中键为id,值为name),现需编写代码实现需求:根据指定id获取对应的name和存储该条信息的数据库名称。
答案结果如下:
from pymysql import *
from pymongo import *
from redis import *
class MySQL(object):
def__init__(self):
self.con = connect(host='localhost', port=3306,
database='stu_info',user='root',
password='mysql',charset='utf8')
self.cur = self.con.cursor()
self.flag = ["mysql", None]
defclose(self):
self.cur.close()
self.con.close()
defcheck(self, sid):
try:
cur = self.cur
param = [sid]
sel_sql = "select name from student where id = %s"
cur.execute(sel_sql, param)
res = cur.fetchone()
ifres:
self.flag[1] = res[0]
exceptException:
pass
finally:
self.close()
return self.flag
class Mongo(object):
def__init__(self):
self.client = MongoClient(host='localhost', port=27017)
self.db = self.client.stu_info
self.col = self.db.student
self.flag = ["mongo", None]
defcheck(self, sid):
try:
res = self.col.find_one({"id": sid})
ifres:
self.flag[1] = res["name"]
exceptException:
pass
finally:
return self.flag
class Redis(object):
def__init__(self):
self.client = StrictRedis()
self.flag = ["redis", None]
defcheck(self, sid):
try:
res = self.client.get(sid)
ifres:
self.flag[1] = res.decode()
exceptException:
pass
finally:
return self.flag
class Check(object):
def__init__(self):
self.msg = ["不在库中", "未找到该学生"]
defcheck(self, sid):
redis= Redis()
self.msg = redis.check(sid)
ifself.msg[1]:
return self.msg
else:
mongo = Mongo()
self.msg = mongo.check(sid)
ifself.msg[1]:
return self.msg
else:
mysql = MySQL()
self.msg = mysql.check(sid)
if self.msg[1]:
return self.msg
else:
self.msg = ["不在库中", "未找到该学生"]
return self.msg
def main():
stu_id =input("请输入要查询的id号:")
check_id =Check()
id_msg =check_id.check(stu_id)
print(id_msg)
if __name__ == '__main__':
main()