python3.4学习笔记(二十五) Python 调用mysql redis实例代码
python3.4学习笔记(二十五) Python 调用mysql redis实例代码
1 #coding: utf-82 __author__ = 'zdz8207'
3 #python2.7
4 import redis, json, re, time
5 import MySQLdb
6 import MySQLdb.cursors
7
8 HOST = "127.0.0.1"
9 USER = "db username"
10 PASSWD = "your password"
11 DB = "your db name"
12 REDIS_DB = redis.Redis(host="127.0.0.1", password="youpassword", port=xxxx)
13
14 import re
15 import random
16 import datetime
17 import traceback
18
19 #update 的直接传sql语句进来
20 def search_by_mysql(sql):
21 data = []
22 try:
23 conn = None
24 #conn = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWD, db=DB) #默认返回元组类型
25 #cursorclass=MySQLdb.cursors.DictCursor 以key:value字典方式返回
26 conn = MySQLdb.connect(host=HOST, user=USER, passwd=PASSWD, db=DB, cursorclass=MySQLdb.cursors.DictCursor)
27 cur = conn.cursor()
28 cur.execute(sql)
29 data = cur.fetchall()
30 cur.close()
31 conn.commit()
32 conn.close()
33 except MySQLdb.Error, e:
34 print "Mysql Error %d: %s" % (e.args[0], e.args[1])
35 return data
36
37 def updateData():
38 print("========== start updateData ===========")
39 # get reddis issues
40 issues = REDIS_DB.hkeys(lottery_type)
41 issues.sort()
42 issue = issues[-1]
43 try:
44 datas = search_by_mysql("SELECT s.id, s.issue,a.numbers FROM search_history AS s JOIN assembly_ssq AS a "\
45 "WHERE s.lottery_type='ssq' AND s.assembly_id=a.id AND s.iscalculate=0 AND s.issue <= %s LIMIT 100" %(issue))
46 #print(datas)
47 except:
48 traceback.print_exc()
49 return
50 if len(datas) == 0:
51 print("========== end update data="+ str(len(datas)))
52 return
53 for data in datas:
54 numbers = data["numbers"]
55 id = data["id"]
56 issue = data["issue"]
57 cur_issue = REDIS_DB.hget(lottery_type, issue)
58 issue_data = json.loads(cur_issue)
59 result = issue_data['result']
60 ismach = 0
61 if numbers == result:
62 ismach = 1
63 try:
64 update_sql = "update search_history set ismach=%s, where id=%s " %(ismach,id)
65 search_by_mysql(update_sql)
66 except:
67 traceback.print_exc()
68 print("========== end update data="+ str(len(datas)))
69
70 if __name__ == "__main__":
71 updateData()
扩展阅读:
python3.4学习笔记(二十四) Python pycharm window安装redis MySQL-python相关方法 - 流风,飘然的风 - 博客园
http://www.cnblogs.com/zdz8207/p/python_learn_note_24.html
以上是 python3.4学习笔记(二十五) Python 调用mysql redis实例代码 的全部内容, 来源链接: utcz.com/z/389104.html