python数据库操作封装_Python封装操作MySQL

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# @Time : 2018/12/6 5:35 PM

# @Author : jiayu.chen

# @Description:

import json

import pymysql

from base.log import Log

class MySQL(object):

logger = Log()

def __init__(self, **config):

try:

self._conn = pymysql.connect(**config)

self._cursor = self._conn.cursor()

except pymysql.Error as e:

self.logger.error("MySQL Error message ".format(e))

def query(self, sql):

try:

result = self._cursor.execute(sql)

except pymysql.Error as e:

self.logger.error("MySQL Error message : ".format(e))

result = False

return result

def select(self, table, column='*', condition=''):

global sql

condition = ' where ' + condition if condition else None

if condition:

try:

sql = "select %s from %s %s" % (column, table, condition)

self.logger.info("要执行的SQL:".format(sql))

except pymysql.Error as e:

self.logger.error("MySQL Error message ".format(e))

else:

try:

sql = "select %s from %s" % (column, table)

self.logger.info("要执行的SQL:".format(sql))

except pymysql.Error as e:

self.logger.error("MySQL Error message ".format(e))

sql = "select %s from %s" % (column, table)

self.query(sql)

return self._cursor.fetchall()

def insert(self, table, tdict):

column = ''

value = ''

for key in tdict:

column += ',' + key

value += "','" + tdict[key]

column = column[1:]

value = value[2:] + "'"

sql = "insert into %s(%s) values(%s)" % (table, column, value)

try:

self._cursor.execute(sql)

self.logger.info("要执行的SQL:".format(sql))

self._conn.commit()

except pymysql.Error as e:

self.logger.error("MySQL Error message ".format(e))

return self._cursor.lastrowid # 返回最后的id

def update(self, table, tdict, condition=''):

if not condition:

self.logger.error("must have condition ")

exit()

else:

condition = 'where ' + condition

value = ''

for key in tdict:

value += ",%s='%s'" % (key, tdict[key])

value = value[1:]

sql = "update %s set %s %s" % (table, value, condition)

try:

self._cursor.execute(sql)

self.logger.info("要执行的SQL:".format(sql))

except pymysql.Error as e:

self.logger.error("MySQL Error message ".format(e))

self.rollback()

# 返回受影响行数

return self.affected_num()

def delete(self, table, condition=''):

if not condition:

self.logger.error("must have condition ")

exit()

else:

condition = 'where ' + condition

# condition = 'where ' + condition if condition else None

sql = "delete from %s %s" % (table, condition)

self._cursor.execute(sql)

self._conn.commit()

# 返回受影响行数

return self.affected_num()

def rollback(self):

self._conn.rollback()

def affected_num(self):

return self._cursor.rowcount

def __del__(self):

try:

self._cursor.close()

self._conn.close()

except:

pass

def close(self):

self.__del__()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值