随笔:Python连接数据库、插入数据方法封装

随笔:Python连接数据库方法封装

from MySQLdb import *
# 连接数据库
class Connect_database(object):
    # 连接数据库
    def __init__(self, host, port, user, password, db, charset='utf8'):
        self.host = host
        self.port = port  # mysql端口
        self.username = user  # mysql远程连接用户名
        self.password = password  # mysql远程连接密码
        self.db = db  # mysql使用的数据库名
        self.charset = charset  # mysql使用的字符编码,默认为utf8
        try:
            self.connect_database = connect(host=self.host, port=self.port, user=self.username, password=self.password, db=self.db, charset=self.charset)
        except:
            print('连接失败')
            
    # 插入数据
    def insert_data(self, batch, name, call_time, status, tablename='table', time_run=None, err_log=None):
        sql = "insert into " + tablename + "(model, call_time, status, time_run, err_log, batch) values('%s', '%s', '%s', '%s', '%s', %d)" 
              % (name, call_time, status, time_run, err_log, batch)
        try:
            cur = self.connect_database.cursor()
            cur.execute(sql)
            self.connect_database.commit()
            cur.close()
            result = sql+'插入成功'
        except Exception as e:
            print('插入失败', e)
            result = sql+'插入失败'
            self.connect_database.rollback()
        return result

    def close_database(self):
        self.connect_database.close()

原文地址:https://www.cnblogs.com/caodingzheng/p/14007078.html