MySQL python Already closed

Проблема состоит в том, что при попытке изменить данные в таблице больше одного раза выходит ошибка

pymysql.err.Error: Already closed

Мой код:

import pymysql
from pymysql.cursors import DictCursor

from configparser import ConfigParser

config = ConfigParser()
config.read('../config.ini')


class Database:
    def __init__(self, db_name):
        self.connection = pymysql.connect(
            host=str(config['db']['host']),
            port=int(config['db']['port']),
            user=str(config['db']['user']),
            password=str(config['db']['password']),
            database=db_name,
            cursorclass=DictCursor
        )
        self.cursor = pymysql.connect.cursor(self.connection)

    def change_local(self, user_id, city, district):
        with self.connection:
            self.cursor.execute("UPDATE `user` SET city = %s, district = %s WHERE user_id = %s",
                                (city, district, user_id, ))
            self.connection.commit()

    def user_exists(self, user_id):
        with self.connection:
            self.cursor.execute("SELECT * FROM `user` WHERE user_id = %s", (user_id, ))
            return self.cursor.fetchone()

    def add_user(self, user_id):
        with self.connection:
            try:
                self.cursor.execute("INSERT INTO `user` (user_id) VALUES (%s)", (user_id, ))
                self.connection.commit()
            except pymysql.err.IntegrityError:
                pass

Как сделать так чтобы данные в таблице сохранялись и соединение не прерывалось? Либо можно создавать новое соединение, но насколько я знаю это относительно дорого и я не совсем понимаю как это лаконично вписать


Ответы (0 шт):