I am having a problem with Python 3.7 PyQt5 QtSql. I am trying to have multiple MSSQL databases connected, but cannot figure how to do it.
I have the following function to connect:
from PyQt5 import QtSql
def connectDb(database_name):
SERVER_NAME = 'COMPUTER\\SQLEXPRESS'
DATABASE_NAME = database_name
connString = f'DRIVER={{SQL Server}};'\
f'SERVER={SERVER_NAME};'\
f'DATABASE={DATABASE_NAME}'
db = QtSql.QSqlDatabase.addDatabase("QODBC")
db.setDatabaseName(connString)
if not db.open():
print(db.lastError().text())
return db
To connect to a database:
db1 = connectDb("Database1")
db2 = connectDb("Database2")
However, when trying to connect to the second database, I get the message:
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
The reason I want to keep multiple databases open is that it is far too slow to keep opening and closing database connections each time I need to query a different database in my code. I'd rather keep them all open and close them when the program exits.