The python class operates the database

First of all, let me talk about why you need to use classes to operate databases

Because when using functions to connect to the database, there is no problem with short-term connections, but [WinError 10048] will be reported for long-term connections. Usually, each socket address (protocol/network address/port) is only allowed to be used once.

The reason is that the maximum number of database connections has been exceeded without disconnecting the database connection. At this time, when you use the command to check the occupancy of port 3306, you will find a large number of TIME_WAIT connections

netstat -aon|findstr "3306"

directly on the code

# 定义一个数据库相关的配置项
DB_CONFIG = {
    'host': '127.0.0.1',
    'user': 'root',
    'password': 'root',
    'port': 3306,
    'db': 'my_db',
    'charset': 'utf8'
}


class SQLManager(object):
    # 连接数据库
    # 将conn,cursor作为类的属性,通过connect方法触发生成
    def __init__(self):
        self.conn = None
        self.cur = None
        self.connect()

    def connect(self):
        self.conn = pymysql.connect(
            host=DB_CONFIG['host'],
            port=DB_CONFIG['port'],
            user=DB_CONFIG['user'],
            password=DB_CONFIG['password'],
            db=DB_CONFIG['db'],
            charset=DB_CONFIG['charset']
        )
        # 检查连接是否存在,断开的话会重连。
        self.conn.ping(reconnect=True)
        # 链接mysql 生成游标对象
        self.cur = self.conn.cursor()

    # 单条增删改数据,创建表
    def modify(self, sql, *args):
        try:
            self.conn.begin()
            self.cur.execute(sql, *args)  # 修改,由arge改为*args
            self.conn.commit()
            print('数据库操作成功!')
            return True
        except pymysql.Error as e:
            print('数据库操作失败:' + str(e))
            self.conn.rollback()

            return False

    # 关闭数据库cursor和连接
    def __del__(self):
        self.cur.close()
        self.conn.close()
        print('数据库成功断开链接!')

say self.conn.ping(reconnect=True)

If you don't add this piece of code, pymysql.err.InterfaceError: (0, '') will be reported when connecting to the database

The reason for this error is that there is no reconnection mechanism for connecting to the database through pymysql. When the connection time exceeds the wait_timeout set by the database, mysql will disconnect. When adding self.conn.ping(reconnect=True), pymysql will check whether the connection is If it exists, it will reconnect if disconnected.

Guess you like

Origin blog.csdn.net/m0_54219225/article/details/128582610