Python基础:Python连接MySQL数据库方法封装2

Python基础:Python连接MySQL数据库方法封装2

之前写过一篇MySQLdb的方法封装,但是因为MySQLdb在Linux上应用较为麻烦,且如果是内网无法连接外网的话下载安装将更为麻烦,甚至无法安装。但是mysql-connector在win和Linux上是通用的,可以直接将其压缩上传到Linux服务器上使用。我就是遇到这样的情况,所以有了2,当然,事实上MySQLdb和mysql-connector方法使用上差别不大

下载mysql-connector库

这里就不做详细讲解了,因为网上有详细教程

方法封装

这里其实有一点需要注意,不能直接from mysql.connector import *。

from mysql import connector
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 = connector.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='cix_alg_routing_inspection', 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()
posted @ 2020-09-27 15:59  caodingzheng  阅读(18)  评论(0编辑  收藏  举报