2

Start

    doadmin.Database().__init__()

Class

class Database(object):
connection = None
cursor = None

def get_c(self): return self.cursor

def init(self): if Database.connection is None: try: Database.connection = mysql.connector.connect(host="stuff", user="stuff", password="stuff", database="stuff", port=stuff) Database.cursor = Database.connection.cursor() except Exception as error: print("Error: Connection not established {}".format(error)) else: print("Connection established")

self.connection = Database.connection
self.cursor = Database.cursor

Request

cursor1 = Database().get_c()

cursor1.execute("SELECT * FROM posts") posts = list(cursor1)

1 Answers1

1

What you have in your question looks perfectly fine (provided the class Database Object is instantiated globally in your application)

To all readers of this post

Opening and Closing DB Connections are expensive operations (See my old post from April 24, 2012 : How costly is opening and closing of a DB connection?)

If you need a persistent connection from a connection pool, I would recommend keeping a global variable with the one DB Connection Object to the Connection Pool as shown above.This will minimize Connection Pool churn (i.e., the Connections Pool's forced closings and reopenings)

RolandoMySQLDBA
  • 185,223
  • 33
  • 326
  • 536