python訪問mysql封裝的常用類實例

字號:


    本文實例講述了python訪問mysql封裝的常用類。分享給大家供大家參考。具體如下:
    python訪問mysql比較簡單,下面整理的就是一個很簡單的python訪問mysql數(shù)據(jù)庫類。
    自己平時也就用到兩個mysql函數(shù):查詢和更新,下面是自己常用的函數(shù)的封裝,大家拷貝過去直接可以使用。
    文件名:dbutil.py
    復(fù)制代碼 代碼如下:# -*- encoding:utf8 -*-
    '''
    @author: crazyant.net
    @version: 2013-10-22
    封裝的mysql常用函數(shù)
    '''
    import mysqldb
    class db():
    def __init__(self, db_host, db_port, db_user, db_pwd, db_name):
    self.db_host = db_host
    self.db_port = db_port
    self.db_user = db_user
    self.db_pwd = db_pwd
    self.db_name = db_name
    self.conn = self.getconnection()
    def getconnection(self):
    return mysqldb.connect(
    host=self.db_host, #設(shè)置mysql地址
    port=self.db_port, #設(shè)置端口號
    user=self.db_user, #設(shè)置用戶名
    passwd=self.db_pwd, #設(shè)置密碼
    db=self.db_name, #數(shù)據(jù)庫名
    charset='utf8' #設(shè)置編碼
    )
    def query(self, sqlstring):
    cursor=self.conn.cursor()
    cursor.execute(sqlstring)
    returndata=cursor.fetchall()
    cursor.close()
    self.conn.close()
    return returndata
    def update(self, sqlstring):
    cursor=self.conn.cursor()
    cursor.execute(sqlstring)
    self.conn.commit()
    cursor.close()
    self.conn.close()
    if __name__==__main__:
    db=db('127.0.0.1',3306,'root','','wordpress')
    print db.query(show tables;)
    使用方法為文件下面的main函數(shù),使用query執(zhí)行select語句并獲取結(jié)果;或者使用update進(jìn)行insert、delete等操作。
    希望本文所述對大家的python程序設(shè)計有所幫助。