[Python] How to initialize a database connection only once and reuse it in run-time in python?

Discussão em 'Python' iniciado por Stack, Novembro 27, 2024.

  1. Stack

    Stack Membro Participativo

    I am currently working on a huge project, which constantly executes queries. My problem is, that my old code always created a new database connection and cursor, which decreased the speed immensivly. So I thought it's time to make a new database class, which looks like this at the moment:

    class Database(object):

    _instance = None

    def __new__(cls):
    if cls._instance is None:
    cls._instance = object.__new__(cls)
    try:
    connection = Database._instance.connection = mysql.connector.connect(host="127.0.0.1", user="root", password="", database="db_test")
    cursor = Database._instance.cursor = connection.cursor()
    except Exception as error:
    print("Error: Connection not established {}".format(error))
    else:
    print("Connection established")
    return cls._instance

    def __init__(self):
    self.connection = self._instance.connection
    self.cursor = self._instance.cursor

    # Do database stuff here


    The queries will use the class like so:

    def foo():
    with Database() as cursor:
    cursor.execute("STATEMENT")


    I am not absolutly sure, if this creates the connection only once regardless of how often the class is created. Maybe someone knows how to initialize a connection only once and how to make use of it in the class afterwards or maybe knows if my solution is correct. I am thankful for any help!

    Continue reading...

Compartilhe esta Página