Hi all,

What's the best way to manage multiple database connections in an application? Specifically, how can I manage which db connection is used for models, queries, &c.?


The documentation says that multiple connections can be declared with a unique name for each on calling addDatabase(). My simple implementation yields errors and doesn't seem to provide a means to load data or call queries on one or the other. For example,

        db2 = QtSql.QSqlDatabase.addDatabase("QPSQL")
        db2.setDatabaseName("foo_db")

        db1 = QtSql.QSqlDatabase.addDatabase("QSQLITE")
        db1.setDatabaseName(":memory:")

This yields the following errors:       

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.

Then creating and setting a data model uses which database?  Both?

        self.theModel = QtSql.QSqlTableModel(self)
        self.theModel.setTable("color")


See the main() method in the attached example.  Thanks in advance!
Scott


#!/usr/bin/env python


import sys, os
from PyQt4 import QtCore, QtGui, QtSql


COLOR_ID, NAME, DESCRIPTION = range(3)



def createFakeData():

	query       = QtSql.QSqlQuery()
	query.exec_("DROP TABLE color")

	query.exec_("""CREATE TABLE color (
				color_id          PRIMARY KEY,
				name VARCHAR(32)  UNIQUE NOT NULL,
				description       TEXT NOT NULL)""")

	query.exec_("INSERT INTO color (name, description) "
				"VALUES ('red', 'this is red')")

	query.exec_("INSERT INTO color (name, description) "
				"VALUES ('green', 'this is green')")

	query.exec_("INSERT INTO color (name, description) "
				"VALUES ('blue', 'this is blue')")



#-------------------------------------------------------------------------------
# class
#-------------------------------------------------------------------------------
class DbTestForm(QtGui.QWidget):
	def __init__(self, parent=None):
		QtGui.QWidget.__init__(self)



		# table model
		# ------------------------------------------------
		self.theModel = QtSql.QSqlTableModel(self)
		self.theModel.setTable("color")
		self.theModel.setSort(NAME, QtCore.Qt.AscendingOrder)
		self.theModel.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit)

		# column headers
		self.theModel.setHeaderData(COLOR_ID, QtCore.Qt.Horizontal, QtCore.QVariant("COLOR_ID"))
		self.theModel.setHeaderData(NAME, QtCore.Qt.Horizontal, QtCore.QVariant("NAME"))
		self.theModel.setHeaderData(DESCRIPTION, QtCore.Qt.Horizontal, QtCore.QVariant("DESCRIPTION"))

		select = self.theModel.select()



		# table view
		# ------------------------------------------------
		self.theView = QtGui.QTableView()
		self.theView.setSortingEnabled(True)
		self.theView.setModel(self.theModel)
		self.theView.setSelectionMode(QtGui.QTableView.SingleSelection)
		self.theView.setSelectionBehavior(QtGui.QTableView.SelectRows)
		self.theView.setColumnHidden(COLOR_ID, True)
		self.theView.resizeColumnsToContents()
		self.theView.horizontalHeader().setStretchLastSection(True)



		# table layout
		# ------------------------------------------------		
		self.tableLayout		= QtGui.QVBoxLayout()
		self.tableLayout.addWidget(self.theView)
		self.setLayout(self.tableLayout)



		# table view selection model
		# ------------------------------------------------
		self.theSelectionModel = self.theView.selectionModel()


		# signals/slots
		# ------------------------------------------------
		self.connect(self.theSelectionModel, QtCore.SIGNAL("selectionChanged(QItemSelection, QItemSelection)"), self.getSelection)



	# methods
	# ------------------------------------------------
	def getSelection(self, selected, deselected):

		currentIndex   = self.theSelectionModel.currentIndex()
		row            = currentIndex.row()
		selectedIndex  = self.theModel.index(row, 2)    # column count starts at 1
		
		print "data:       ", self.theModel.data(currentIndex).toString()
		print "row:        ", currentIndex.row()
		print "row data:   ", self.theModel.data(selectedIndex).toString()



#-------------------------------------------------------------------------------
# main
#-------------------------------------------------------------------------------
if __name__ == "__main__":
	app = QtGui.QApplication(sys.argv)

	db2 = QtSql.QSqlDatabase.addDatabase("QPSQL")
	db2.setDatabaseName("foo_db")

	db1 = QtSql.QSqlDatabase.addDatabase("QSQLITE")
	db1.setDatabaseName(":memory:")

	
	if not db1.open():
		QtGui.QMessageBox.warning(None, "Test",
			QtCore.QString("Database Error: %1").arg(db1.lastError().text()))
		sys.exit(1)
	
	ok = db1.open()
	print "db1 connection:	", ok

	createFakeData()
	form = DbTestForm()
	form.setWindowTitle("Db Test")
	form.show()
	sys.exit(app.exec_())
		





_______________________________________________
PyQt mailing list    [email protected]
http://www.riverbankcomputing.com/mailman/listinfo/pyqt

Reply via email to