python2.7脚本连接MongoDB、redis、mysql的操作

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)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值