python-db 프로필

5638 단어
#!/usr/bin/python27
# -*- encoding: utf-8 -*-

import sys
import ConfigParser
import MySQLdb
import MySQLdb.cursors

cf = ConfigParser.ConfigParser()
cf.read("/tmp/report/dbs.conf")
ouser = cf.get('client','user')
opwd = cf.get('client','password')
ohost = cf.get('client','host')
oport = cf.get('client','port')
odb = cf.get('client','database')

def mysqlLib(sql,host=ohost,port=oport,db=odb,user=ouser,pwd=opwd):
    try:
        con = MySQLdb.connect(host, user,pwd, db,charset="utf8");
        cur = con.cursor()
        cur.execute(sql)
        data = cur.fetchall()
        con.close()
        return data
    except Exception as e:
        print e



def mysqlDictLib(sql,host=ohost,port=oport,db=odb,user=ouser,pwd=opwd):
    try:
        con = MySQLdb.connect(host, user,pwd, db,cursorclass = MySQLdb.cursors.DictCursor,charset="utf8");
        cur = con.cursor()
        cur.execute(sql)
        data = cur.fetchall()
        con.close()
        return data
    except Exception as e:
        print e






if __name__ == '__main__':
    sql = 'select name from members where id in (select member_id from member_tags where tags_id=199      ) limit 5 '
    # db = mysqlLib(sql)
    db = mysqlDictLib(sql)
    print db[0]["name"]
[client]
database=xxx
user=xx
password=xx
port=3306
host=xxx

좋은 웹페이지 즐겨찾기