MySQL connection (Question)
romkazor opened this issue · 5 comments
Hello. How can i create a permanent connection to database with aiodbc and use it for all queries like this:
cnxn = pyodbc.connect(...)
cursor = cnxn.cursor()
cursor.execute(...)
I don't want to create a new connection to the database every time to make a query.
Thanks.
You can create a singleton class that keeps the connection open. The class should have a method that returns the cursor i.e. def cursor(self): return self.conneciton.cursor(), as this is what you need in order to execute a query. I hope, that helps.
Thanks. If you could write an some small example, its will be great.
Singletons should be avoided, it is code smell in most of cases. aioodbc provides connection pooling for this purposes.
aioodbc/examples/example_pool.py
Lines 1 to 22 in 0124556
This is how I use it:
class DatabaseConnection:
instance = None
def __init__(self, connection):
self.connection = connection
def cursor(self):
"Form the cursor"
return self.connection.cursor()
@classmethod
async def get(cls):
"Return database connection"
if cls.instance is None:
connection = await connect("Connection detailes here - DSN")
cls.instance = DatabaseConnection(connection)
return cls.instance