python mysql类

import MySQLdb

class MySql():
    conn = ''
    cursor = ''
    def __init__(self, host, user, passwd, db, charset):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.db = db
        self.charset = charset
        self.connect()

    def connect(self):
        self.conn = MySQLdb.connect(host=self.host,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset)
        self.cursor = self.conn.cursor()

    def query(self, sql):
        return self.cursor.execute(sql)

    def show(self):
        return self.cursor.fetchall()

    def select(self):
        fieldname = [d[0].lower() for d in self.cursor.description]
        while True:
            rows = self.show()
            if not rows: break
            for row in rows:
                yield dict(zip(fieldname, row))

    def __del__(self):
        self.cursor.commit()
        self.cursor.close()
        self.conn.close()


#测试
mysql = MySql('localhost', 'root', '', 'el_game', 'utf8')

mysql.query("SELECT * FROM users limit 1")
posted @ 2012-09-17 17:09  tywei  阅读(195)  评论(0)    收藏  举报