Python笔记(二) -- Python封装数据库

简单封装了python中使用MySQL数据的操作。

#Python连接MySQL数据库
import MySQLdb

class Getdb():
    def __init__(self, host, user, passwd, db, charset):
        try:
            self.conn = MySQLdb.connect(host='host',user='user',passwd='passwd',db='db',charset="charset")
            self.cursor = self.conn.cursor()
        except Exception, e:
            sys.exit()

    def selectInfo(self,sql):
        try:
            n = self.cursor.execute(sql)
            if n != 0:
                data = self.cursor.fetchall()
            else:
                data = "N-DATA"
                self.logger.log('warn', 'No Data found from DB!, SQL:<' + sql + '>')
        except Exception, e:
            data = "S-ERROR"
        return data

    def selectInfoWithArgs(self,sql,param):
        try:
            n = self.cursor.execute(sql,param)
            if n != 0:
                data = self.cursor.fetchall()
            else:
                data = "N-DATA"
        except Exception:
            data = "S-ERROR"
        return data

    def executeSQLWithArgs(self,sql,param):
        try:
            self.cursor.execute(sql,param)
            self.conn.commit()
            result = "I-SUCESS"
        except Exception, e:
            result = "I-FAIL"
        return result

    def executeSQL(self,sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            result = "I-SUCESS"
        except Exception, e:
            result = "I-FAIL"
        return result

    def close(self):
        ''' 关闭连接 '''
        self.cursor.close()
        self.conn.close()

使用:

conn = DBManager.Getdb(host, user, passwd, db, charset)
data = conn.selectInfo(selectsql)
#param = (arg1, arg2)
#data = conn.selectInfoWithArgs(selectsql, param)
conn.close()
if data != “S-ERROR” and data != “N-DATA”:
for d in data:
func()

ret = conn.executeSQL(updateSql)
#param = (arg1, arg2)
#data = conn.executeSQLWithArgs(updateSql, param)
if ret != “I-SUCESS”:
logger.error(“DB operate failed, result:%s” % ret)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值