python3.4学习笔记(二十五) Python 调用mysql redis实例代码

时间:2021-07-06 03:00:20

python3.4学习笔记(二十五) Python 调用mysql redis实例代码

 #coding: utf-8
__author__ = 'zdz8207'
#python2.7
import redis, json, re, time
import MySQLdb
import MySQLdb.cursors HOST = "127.0.0.1"
USER = "db username"
PASSWD = "your password"
DB = "your db name"
REDIS_DB = redis.Redis(host="127.0.0.1", password="youpassword", port=xxxx) import re
import random
import datetime
import traceback #update 的直接传sql语句进来
def search_by_mysql(sql):
data = []
try:
conn = None
#conn = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWD, db=DB) #默认返回元组类型
#cursorclass=MySQLdb.cursors.DictCursor 以key:value字典方式返回
conn = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWD, db=DB, cursorclass=MySQLdb.cursors.DictCursor)
cur = conn.cursor()
cur.execute(sql)
data = cur.fetchall()
cur.close()
conn.commit()
conn.close()
except MySQLdb.Error, e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
return data def updateData():
print("========== start updateData ===========")
# get reddis issues
issues = REDIS_DB.hkeys(lottery_type)
issues.sort()
issue = issues[-1]
try:
datas = search_by_mysql("SELECT s.id, s.issue,a.numbers FROM search_history AS s JOIN assembly_ssq AS a "\
"WHERE s.lottery_type='ssq' AND s.assembly_id=a.id AND s.iscalculate=0 AND s.issue <= %s LIMIT 100" %(issue))
#print(datas)
except:
traceback.print_exc()
return
if len(datas) == 0:
print("========== end update data="+ str(len(datas)))
return
for data in datas:
numbers = data["numbers"]
id = data["id"]
issue = data["issue"]
cur_issue = REDIS_DB.hget(lottery_type, issue)
issue_data = json.loads(cur_issue)
result = issue_data['result']
ismach = 0
if numbers == result:
ismach = 1
try:
update_sql = "update search_history set ismach=%s, where id=%s " %(ismach,id)
search_by_mysql(update_sql)
except:
traceback.print_exc()
print("========== end update data="+ str(len(datas))) if __name__ == "__main__":
updateData()

扩展阅读:

python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法 - 流风,飘然的风 - 博客园
http://www.cnblogs.com/zdz8207/p/python_learn_note_24.html