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
  • 182,700
  • 33
  • 317
  • 520
  • i’m a bit confused. i call the unit function in the create_app function, and then i just create a Database object in other function. should i instrad make a database object and just use that one object throughout the program? – Corie LeClair Jul 28 '23 at 21:55
  • The create_app function should include the call to create the Database Object, That way you are using just one DB Connection. – RolandoMySQLDBA Jul 29 '23 at 02:00
  • do i need to use that one object? or can i create new objects? – Corie LeClair Jul 29 '23 at 03:25
  • That depends on the number of databases in the mysql instance the application needs. If you have db1, db2, db3, you could create a global Database object for each database if your application needs it. Alternatively, you could.create one Database object, but you would have to switch the target database back and forth as needed.

    Whichever way you choose, Please prep this in Staging, test it, and get a good feel for using one or more Dayanase objects.

    – RolandoMySQLDBA Jul 29 '23 at 10:38