python操作数据库学习,自封装一个类来处理


自封装一个简单的类来测试一下,挺不错。。。



import MySQLdb


class WebSiteDB:
    def __init__(self, dbname = 'website', hostname = 'localhost', username = 'root', password = 'test'):
        self.dbname = dbname
        self.hostname = hostname
        self.username = username
        self.password = password
        self.conn = None
        self.cursor = None
        self.__connectMySql()
        self.__createDB()
        self.__selectDB()

    def __connectMySql(self):
        try:
            self.conn = MySQLdb.connect(host = self.hostname, user = self.username, passwd = self.password)
            self.cursor = self.conn.cursor()
        except:
            print 'fail to connect to MySQLdb '

    def __createDB(self):
        try:
            sqlcmd = 'create database if not exists ' + self.dbname
            self.cursor.execute(sqlcmd)
        except:
            print 'fail to create database ' + self.dbname
            return None
        
    def __selectDB(self):
        try:
            self.conn.select_db(self.dbname)
        except:
            print 'fail to select_db ', self.dbname

    def createTable(self, tablename):
        try:
            if tablename is None:
                return None
            sqlcmd = 'create table if not exists ' + tablename + '(website varchar(50), url varchar(300))'
            self.cursor.execute(sqlcmd)
        except:
            print 'fail to create table ' + tablename
            return None

    def fetchOne(self, tablename):
        try:
            self.cursor.execute('select * from ' + tablename)
            result = self.cursor.fetchone()
            return result
        except:
            print 'fail to fetchOne'
            return None

    def fetchMany(self, tablename, num):
        try:
            self.cursor.execute('select * from ' + tablename)
            results = self.cursor.fetchmany(num)
            return results
        except:
            print 'fail to fetchMany ', num
            return None

    def fetchAll(self, tablename):
        try:
            self.cursor.execute('select * from ' + tablename)
            results = self.cursor.fetchall()
            return results
        except:
            print 'fail to fetchAll'
            return None
    
    def insertOneRd(self, tablename, value):
        try:
            sqlcmd = 'insert into ' + tablename + ' values(%s, %s)'
            self.cursor.execute(sqlcmd, value);
        except:
            print 'fail to insertOneRd'
            return None

    def insertManyRd(self, tablename, values):
        try:
            sqlcmd = 'insert into ' + tablename + ' values(%s, %s)'
            self.cursor.executemany(sqlcmd, values)
        except:
            print 'fail to insetManyRd'
            return None

    def droptable(self, tablename):
        while True:
            self.cursor.execute('show tables like "%s%%"' % tablename)
            tables = self.cursor.fetchall()
            if len(tables) == 0:
                break
            for x in tables:
                try:
                    self.cursor.execute('drop table %s' % x)
                    self.conn.commit()
                except:
                    continue




### Python 数据库操作封装的方法 对于Python连接并操作多种型的数据库(如MySQL、SQL Server、Oracle以及PostgreSQL),可以采用统一的方式来进行封装,从而简化开发流程并提升代码复用率。为了达到这一目标,通常会创建一个专门用于处理不同种数据库连接及查询执行的基础。 #### 使用`DBUtils`作为通用解决方案 一种常见的做法是利用现有的开源项目——比如 `dbutils` ,它提供了持久化管理器模式下的线程安全连接池功能[^1]。然而,在实际应用中更常见的是开发者基于特定需求自定义适合自己的轻量级工具包。 #### 自定义简易版ORM框架 考虑到灵活性与性能之间的平衡,很多情况下会选择构建一套简易的对象关系映射(ORM)机制来抽象底层SQL逻辑。下面是一个针对 MySQL 的例子: ```python import pymysql class MysqlHelper(object): def __init__(self, host='localhost', port=3306, user=None, password=None, database=None): self.host = host self.port = port self.user = user self.password = password self.database = database def get_conn(self): conn = pymysql.connect( host=self.host, port=int(self.port), user=self.user, passwd=self.password, db=self.database, charset="utf8" ) return conn def execute_sql(self, sql_str, params=None): try: with self.get_conn() as connection: cursor = connection.cursor() if isinstance(params, (list,tuple)): affected_rows = cursor.executemany(sql_str,params) elif params is not None: affected_rows = cursor.execute(sql_str,params) else: affected_rows = cursor.execute(sql_str) result_set = [] if 'select' in sql_str.lower(): columns = [desc[0] for desc in cursor.description] rows = cursor.fetchall() for row in rows: item_dict = dict(zip(columns,row)) result_set.append(item_dict) connection.commit() return {"affected": affected_rows,"data":result_set} except Exception as e: raise RuntimeError(f"Error executing SQL statement {e}") ``` 上述代码片段展示了如何通过继承对象的方式来建立与 MySQL 数据库间的交互接口,并实现了基本的 CRUD 功能[^3]。值得注意的是,这段程序还考虑到了异常情况的发生,并采取了相应的措施确保事务的一致性和安全性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值