欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python連接MySQL、MongoDB、Redis、memcache等數(shù)據(jù)庫的方法

 更新時(shí)間:2013年11月15日 16:41:43   作者:  
這篇文章主要介紹了python連接操作MySQL、MongoDB、Redis、memcache等數(shù)據(jù)庫的方法,大家可以參考使用

用Python寫腳本也有一段時(shí)間了,經(jīng)常操作數(shù)據(jù)庫(MySQL),現(xiàn)在就整理下對(duì)各類數(shù)據(jù)庫的操作,如后面有新的參數(shù)會(huì)補(bǔ)進(jìn)來,慢慢完善。

一,python 操作 MySQL:詳情見:
【apt-get install python-mysqldb】

復(fù)制代碼 代碼如下:

#!/bin/env python
# -*- encoding: utf-8 -*-
#-------------------------------------------------------------------------------
# Purpose:     example for python_to_mysql
# Author:      zhoujy
# Created:     2013-06-14
# update:      2013-06-14
#-------------------------------------------------------------------------------
import MySQLdb
import os

#建立和數(shù)據(jù)庫系統(tǒng)的連接,格式
#conn   = MySQLdb.connect(host='localhost',user='root',passwd='123456',db='test',port=3306,charset='utf8')

#指定配置文件,確定目錄,或則寫絕對(duì)路徑
cwd = os.path.realpath(os.path.dirname(__file__))
db_conf = os.path.join(cwd, 'db.conf')
conn   = MySQLdb.connect(read_default_file=db_conf,host='localhost',db='test',port=3306,charset='utf8')

#要執(zhí)行的sql語句
query  = 'select id  from t1'

#獲取操作游標(biāo)
cursor = conn.cursor()

#執(zhí)行SQL
cursor.execute(query)

#獲取一條記錄,每條記錄做為一個(gè)元組返回,返回3,游標(biāo)指到第2條記錄。
result1 = cursor.fetchone()
for i in result1:
    print i
#返回影響的行數(shù)
    print cursor.rowcount

#獲取指定數(shù)量記錄,每條記錄做為一個(gè)元組返回,返回1,2,游標(biāo)從第2條記錄開始,游標(biāo)指到第4條記錄。
result2 = cursor.fetchmany(2)
for i in result2:
    for ii in i:
        print ii


#獲取所有記錄,每條記錄做為一個(gè)元組返回,返回3,4,7,6,游標(biāo)從第4條記錄開始到最后。
result3 = cursor.fetchall()
for i in result3:
    for ii in i:
        print ii

#獲取所有記錄,每條記錄做為一個(gè)元組返回,返回3,4,7,6,游標(biāo)從第1條記錄開始
#重置游標(biāo)位置,0為偏移量,mode=absolute | relative,默認(rèn)為relative
cursor.scroll(0,mode='absolute')
result3 = cursor.fetchall()
for i in result3:
    for ii in i:
        print ii

#以下2種方法都可以把數(shù)據(jù)插入數(shù)據(jù)庫:
#(one)
for i in range (10,20):
    query2 = 'insert into t1 values("%d",now())' %i
    cursor.execute(query2)
    #提交
    conn.rollback()
#(two)
rows = []
for i in range (10,20):
    rows.append(i)
query2 = 'insert into t1 values("%s",now())'
#executemany 2個(gè)參數(shù),第2個(gè)參數(shù)是變量。
cursor.executemany(query2,rows)
#提交
conn.commit()

#選擇數(shù)據(jù)庫
query3 = 'select id from dba_hospital'
#重新選擇數(shù)據(jù)庫
conn.select_db('chushihua')

cursor.execute(query3)

result4 = cursor.fetchall()
for i in result4:
    for ii in i:
        print ii
#不定義query,直接執(zhí)行:
cursor.execute("set session binlog_format='mixed'")

#關(guān)閉游標(biāo),釋放資源
cursor.close()

'''
+------+---------------------+
| id   | modifyT             |
+------+---------------------+
|    3 | 2010-01-01 00:00:00 |
|    1 | 2010-01-01 00:00:00 |
|    2 | 2010-01-01 00:00:00 |
|    3 | 2010-01-01 00:00:00 |
|    4 | 2013-06-04 17:04:54 |
|    7 | 2013-06-04 17:05:36 |
|    6 | 2013-06-04 17:05:17 |
+------+---------------------+

'''

注意:在腳本中,密碼寫在腳本里面很容易暴露,這樣可以用一個(gè)配置文件的方式來存密碼,如db.conf:

復(fù)制代碼 代碼如下:

[client]
user=root
password=123456

二,python 操作 MongoDB:

復(fù)制代碼 代碼如下:

#!/bin/env python
# -*- encoding: utf-8 -*-
#-------------------------------------------------------------------------------
# Purpose:     example for python_to_mongodb
# Author:      zhoujy
# Created:     2013-06-14
# update:      2013-06-14
#-------------------------------------------------------------------------------
import pymongo
import os

#建立和數(shù)據(jù)庫系統(tǒng)的連接,創(chuàng)建Connection時(shí),指定host及port參數(shù)
conn   = pymongo.Connection(host='127.0.0.1',port=27017)

#admin 數(shù)據(jù)庫有帳號(hào),連接-認(rèn)證-切換庫
db_auth = conn.admin
db_auth.authenticate('sa','sa')
#連接數(shù)據(jù)庫
db = conn.abc

#連接表
collection = db.stu

#查看全部表名稱
db.collection_names()
#print db.collection_names()

#訪問表的數(shù)據(jù),指定列
item = collection.find({},{"sname":1,"course":1,"_id":0})
for rows in item:
    print rows.values()

#訪問表的一行數(shù)據(jù)
print collection.find_one()

#得到所有的列
for rows in collection.find_one():
    print rows

#插入
collection.insert({"sno":100,"sname":"jl","course":{"D":80,"S":85}})
#或
u = dict(sno=102,sname='zjjj',course={"D":80,"S":85})
collection.insert(u)

#得到行數(shù)
print collection.find().count()
print collection.find({"sno":100})

#排序,按照某一列的值。pymongo.DESCENDING:倒序;pymongo.ASCENDING:升序。按照sno倒序
item = collection.find().sort('sno',pymongo.DESCENDING)
for rows in item:
    print rows.values()

#多列排序
item = collection.find().sort([('sno',pymongo.DESCENDING),('A',pymongo.ASCENDING)])

#更新,第一個(gè)參數(shù)是條件,第二個(gè)參數(shù)是更新操作,$set,%inc,$push,$ne,$addToSet,$rename 等
collection.update({"sno":100},{"$set":{"sno":101}})
#更新多行和多列
collection.update({"sno":102},{"$set":{"sno":105,"sname":"SSSS"}},multi=True)

#刪除,第一個(gè)參數(shù)是條件,第二個(gè)參數(shù)是刪除操作。
collection.remove({"sno":101})

'''
sno:學(xué)號(hào);sname:姓名;course:科目

db.stu.insert({"sno":1,"sname":"張三","course":{"A":95,"B":90,"C":65,"D":74,"E":100}})
db.stu.insert({"sno":2,"sname":"李四","course":{"A":90,"B":85,"X":75,"Y":64,"Z":95}})
db.stu.insert({"sno":3,"sname":"趙五","course":{"A":70,"B":56,"F":85,"G":84,"H":80}})
db.stu.insert({"sno":4,"sname":"zhoujy","course":{"A":64,"B":60,"C":95,"T":94,"Y":85}})
db.stu.insert({"sno":5,"sname":"abc","course":{"A":87,"B":70,"Z":56,"G":54,"H":75}})
db.stu.insert({"sno":6,"sname":"楊六","course":{"A":65,"U":80,"C":78,"R":75,"N":90}})
db.stu.insert({"sno":7,"sname":"陳二","course":{"A":95,"M":68,"N":84,"S":79,"K":89}})
db.stu.insert({"sno":8,"sname":"zhoujj","course":{"P":90,"B":77,"J":85,"K":68,"L":80}})
db.stu.insert({"sno":9,"sname":"ccc","course":{"Q":85,"B":86,"C":90,"V":87,"U":85}})

'''

計(jì)算Mongodb文檔中各集合的數(shù)目:

復(fù)制代碼 代碼如下:

import pymongo

conn   = pymongo.Connection(host='127.0.0.1',port=27017)
db = conn.abc    #abc文檔
for tb_name in db.collection_names():     #循環(huán)出各集合名
    Count = db[tb_name].count()            #計(jì)算各集合的數(shù)量
    if Count > 2:                                 #過濾條件
        print tb_name + ':' + str(Count)

'''
conn   = pymongo.Connection(host='127.0.0.1',port=27017)
db = conn.abc
for tb_name in db.collection_names():
    print tb_name + ':'
    exec('print ' + 'db.'+tb_name+'.count()')      #變量當(dāng)集合的處理方式

OR

conn   = pymongo.Connection(host='127.0.0.1',port=27017)
db = conn.abc
for tb_name in db.collection_names():
    mon_dic=db.command("collStats", tb_name)      #以字典形式返回
    print mon_dic.get('ns'),mon_dic.get('count')

'''

三,python 操作 Redis:

復(fù)制代碼 代碼如下:

#!/bin/env python
# -*- encoding: utf-8 -*-
#-------------------------------------------------------------------------------
# Purpose:     example for python_to_mongodb
# Author:      zhoujy
# Created:     2013-06-14
# update:      2013-06-14
#-------------------------------------------------------------------------------

import redis

f = open('aa.txt')
while True:
    line = f.readline().strip().split(' # ')
    if line == ['']:
        break
    UserName,Pwd,Email = line
#    print name.strip(),pwd.strip(),email.strip()
    rc = redis.StrictRedis(host='127.0.0.1',port=6379,db=15)
    rc.hset('Name:' + UserName,'Email',Email)
    rc.hset('Name:' + UserName,'Password',Pwd)
f.close()

alluser = rc.keys('*')
#print alluser
print "===================================讀出存進(jìn)去的數(shù)據(jù)==================================="
for user in alluser:
    print ' # '.join((user.split(':')[1],rc.hget(user,'Password'),rc.hget(user,'Email')))

四,python 操作 memcache:

復(fù)制代碼 代碼如下:

import memcache
mc = memcache.Client(['127.0.0.1:11211'],debug=1)

復(fù)制代碼 代碼如下:

#!/usr/bin/env python
#coding=utf-8
import MySQLdb
import memcache
import sys
import time

def get_data(mysql_conn):
#    nn = raw_input("press string name:")
    mc = memcache.Client(['127.0.0.1:11211'],debug=1)
    t1 =time.time()
    value = mc.get('zhoujinyia')
    if value == None:
        t1 = time.time()
        print t1
        query = "select company,email,sex,address from uc_user_offline where realName = 'zhoujinyia'"
        cursor= mysql_conn.cursor()
        cursor.execute(query)
        item = cursor.fetchone()
        t2 = time.time()
        print t2
        t = round(t2-t1)
        print "from mysql cost %s sec" %t
        print item
        mc.set('zhoujinyia',item,60)
    else :
        t2 = time.time()
        t=round(t2-t1)
        print "from memcache cost %s sec" %t
        print value
if __name__ =='__main__':
    mysql_conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='123456',db='member',port=3306,charset='utf8')
    get_data(mysql_conn)

相關(guān)文章

  • Python文件與文件夾操作大全(非常全面)

    Python文件與文件夾操作大全(非常全面)

    Python具有強(qiáng)大的文件處理功能,如文件的創(chuàng)建、打開、文件內(nèi)容的寫入、讀出文件中的內(nèi)容等等,這篇文章主要介紹了Python文件與文件夾操作,需要的朋友可以參考下
    2023-09-09
  • Python實(shí)現(xiàn)檢測文件的MD5值來查找重復(fù)文件案例

    Python實(shí)現(xiàn)檢測文件的MD5值來查找重復(fù)文件案例

    這篇文章主要介紹了Python實(shí)現(xiàn)檢測文件的MD5值來查找重復(fù)文件案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • 解決python讀取幾千萬行的大表內(nèi)存問題

    解決python讀取幾千萬行的大表內(nèi)存問題

    今天小編就為大家分享一篇解決python讀取幾千萬行的大表內(nèi)存問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • python?生成唯一id的四種方式

    python?生成唯一id的四種方式

    本文主要介紹了python?生成唯一id的四種方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02
  • 二十種Python代碼游戲源代碼分享

    二十種Python代碼游戲源代碼分享

    這篇文章主要介紹了二十種Python代碼游戲源代碼分享,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-04-04
  • Python 實(shí)現(xiàn)數(shù)組相減示例

    Python 實(shí)現(xiàn)數(shù)組相減示例

    今天小編就為大家分享一篇Python 實(shí)現(xiàn)數(shù)組相減示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • python f-string式格式化聽語音流程講解

    python f-string式格式化聽語音流程講解

    在本篇文章中小編給大家整理的是關(guān)于python f-string式格式化聽語音的相關(guān)知識(shí)點(diǎn)內(nèi)容,有興趣的朋友們學(xué)習(xí)下。
    2019-06-06
  • python?scrapy框架的日志文件問題

    python?scrapy框架的日志文件問題

    這篇文章主要介紹了python?scrapy框架的日志文件問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • Python 批量讀取文件中指定字符的實(shí)現(xiàn)

    Python 批量讀取文件中指定字符的實(shí)現(xiàn)

    這篇文章主要介紹了Python 批量讀取文件中指定字符的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • Python使用redis pool的一種單例實(shí)現(xiàn)方式

    Python使用redis pool的一種單例實(shí)現(xiàn)方式

    這篇文章主要介紹了Python使用redis pool的一種單例實(shí)現(xiàn)方式,結(jié)合實(shí)例形式分析了Python操作redis模塊實(shí)現(xiàn)共享同一個(gè)連接池的相關(guān)技巧,需要的朋友可以參考下
    2016-04-04

最新評(píng)論