python的mysqldb封装类(转)

转自:

http://blog.csdn.net/serverxp/article/details/6958459

 

#===============================================================================
# -*- coding: utf-8 -*-
#MySQLdb封装类
#author:paul wang
#===============================================================================

import MySQLdb as mdb

class myMySQL:

    def connect(self,host="localhost",user="root",pwd="",database="",autocommit=False):
        try:
            self.isConnect = False

            self.conn = mdb.connect( host, user,
                pwd, database);

            self.isConnect = True

            self.cursor = self.conn.cursor()
            self.cursor.execute("SELECT VERSION()")

            data = self.cursor.fetchone()

            if autocommit:
                self.conn.autocommit(True)
            else:
                self.conn.autocommit(False)

        except mdb.Error as e:
            print ( "Connect Error %d: %s" % (e.args[0],e.args[1]) )

        print ( "Database version : %s " % data )

    def close(self):
        try:
            self.cursor.close()
            self.conn.close()
        except mdb.Error as e:
            print ( "Close Error %d: %s" % (e.args[0],e.args[1]) )

    def excute(self,sql=""):
        try:
            self.cursor.execute(sql)
        except mdb.Error as e:
            print ( "Excute Error %d: %s" % (e.args[0],e.args[1]) )
            print ( "Excute sql= %s" % sql )

    def getrows(self,sql):
        try:
            self.excute(sql)
            rows = self.cursor.fetchall()
            return rows
        except mdb.Error as e:
            print ( "getrows Error %d: %s" % (e.args[0],e.args[1]) )   

    def selectDB(self,dbName):
        self.conn.select_db(dbName)

    def commit(self):
        self.conn.commit()

    def rollback(self):
        self.conn.rollback()

    def setautocommit(self,auto=False):
        self.conn.autocommit(auto)

    def isConnected(self):
        return self.isConnect

#下面是测试代码
#db = myMySQL()
#db.connect( "localhost","root","","drupal",False )
#db.setautocommit(False)
#db.excute("insert into test values(2)")
#db.rollback()
#rows = db.getrows("select * from test where 1 = 1 ")
#print( rows )
#db.close()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python数据封装是将数据库操作相关的代码封装成一个模块或,使得代码结构更加清晰,易于维护和重用。常用的Python数据库封装模块有: 1. PyMySQL:一个纯Python实现的MySQL客户端库,支持Python 2和Python 3。 2. MySQLdbPython MySQL数据库接口,是Python的一个第三方模块,用于连接MySQL数据库。 3. SQLAlchemy:一个Python SQL工具和对象关系映射器,支持多种数据库,包括MySQL、PostgreSQL、SQLite、Oracle等。 4. Django ORM:一个Python Web框架,自带ORM(对象关系映射器),支持多种数据库,包括MySQL、PostgreSQL、SQLite等。 封装后的代码示例: ``` import pymysql class DB: def __init__(self, host, user, password, database): self.conn = pymysql.connect( host=host, user=user, password=password, database=database, charset='utf8' ) def query(self, sql): cursor = self.conn.cursor() cursor.execute(sql) result = cursor.fetchall() cursor.close() return result def insert(self, table, data): cursor = self.conn.cursor() keys = ','.join(data.keys()) values = ','.join(['%s'] * len(data)) sql = 'INSERT INTO %s (%s) VALUES (%s)' % (table, keys, values) cursor.execute(sql, tuple(data.values())) self.conn.commit() cursor.close() def update(self, table, data, condition): cursor = self.conn.cursor() values = ','.join(["%s='%s'" % (k, v) for k, v in data.items()]) sql = 'UPDATE %s SET %s WHERE %s' % (table, values, condition) cursor.execute(sql) self.conn.commit() cursor.close() def delete(self, table, condition): cursor = self.conn.cursor() sql = 'DELETE FROM %s WHERE %s' % (table, condition) cursor.execute(sql) self.conn.commit() cursor.close() def close(self): self.conn.close() ``` 以上代码是一个封装MySQL数据库操作的,包括查询、插入、更新和删除等常用操作。使用时只需实例化DB,并调用对应的方法即可完成数据库操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值