1.首先建立一个db.py用来专门连接这些基本的库
# -*- coding: utf-8 -*-
import MySQLdb
import MySQLdb.cursors
import redis
from pymongo import MongoClient
mongoUrl = 'mongodb://root:localhost:3717/?authSource=admin'
mongo_db = MongoClient(mongoUrl)
config_slive = {
'host': 'localhost',
'port': 3306,
'user': 'slive',
'passwd': '123456',
'charset': 'utf8',
'db': 'slive',
'cursorclass': MySQLdb.cursors.DictCursor
}
r_slive = redis.StrictRedis(host='localhost', port=6379, db=0, password='123456')
db_slive= MySQLdb.connect(**config_slive)
2.操作mongoDB、mysql
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
from db import *
def query():
//操作mysql
cur.execute('select uid,room_id,num from table')
result=cur.fetchall()
for data in result:
//操作mongodb
user = mongo_db.userdata['userprofile'].find_one({'uid':data['uid']})
name=''
try:
name=user['name']
except KeyError:
name=''
print '%s| %s| %s|%s' % (data['uid'],data['room_id'],name,data['num'])
query()
3.操作redis
# -*- coding: utf-8 -*-
import json
from db import *
s1 = r_slive.get('redisKey')
cur = db_slive.cursor()
j1 = json.loads(s1)
def query(data):
for marOne in data:
cur.execute("SELECT uid,room_id from t_slive_room_info where uid =" + marOne['uid'])
user = cur.fetchone()
name=''
try:
name=marOne['nickname']
except KeyError:
name=''
room_id = str(user['room_id'])
print '%s, %s, %s, %s,%s' % (marOne['rank'],marOne['uid'],room_id,name, marOne['score'])
query(j1)
4.操作redis的zset(不需要json.loads)
# -*- coding: utf-8 -*-
import json
from db import *
import time
import datetime
s1 = r_slive_user.zrange('paopao_user_room_closure_list',0,-1,withscores=True)
cur = db_slive.cursor()
def query(data):
for user in data:
cur.execute("SELECT room_id from t_slive_room_info where uid =" + user[0])
timeStamp = int(user[1])/1000
x = time.localtime(timeStamp)
otherStyleTime=time.strftime('%Y-%m-%d %H:%M:%S',x)
room = cur.fetchone()
room_id = str(room['room_id'])
print '%s, %s,%s' % (user[0],room_id,otherStyleTime)
query(s1)