I have two issues - first off (and more importantly) the second time the code is run from the QGIS Python it fails with "The thread tried to read from or write to a virtual address for which it does not have the appropriate access".
The second issue is that if I close and remove the database the table displayed using projectView.show() is empty yet if I comment those lines out, the data displays correctly.
from PyQt4.QtSql import *
from PyQt4.QtGui import *
from qgis.gui import *
db = QSqlDatabase.addDatabase('QODBC')
if db.isValid():
db.setDatabaseName('DRIVER={SQL Server};SERVER=%s;DATABASE=%s;UID=%s;PWD=%s;'
% ('ServerName',
'Database',
'username',
'password'))
#print "db.isValid"
if db.open():
#print "success"
query = db.exec_("""SELECT TOP 100 postal_address as address, EASTING as x, NORTHING as y FROM dbo.POSTAL_ADDRESS WHERE postal_address LIKE('%EX3 %')""")
projectModel = QSqlQueryModel()
projectModel.setQuery(query)
projectView = QTableView()
projectView.setModel(projectModel)
projectView.show()
QMessageBox.warning(None, "Info", "hello")
query = db.exec_("""SELECT TOP 100 postal_address as address, EASTING as x, NORTHING as y FROM dbo.POSTAL_ADDRESS WHERE postal_address LIKE('%EX2 %')""")
projectModel = QSqlQueryModel()
projectModel.setQuery(query)
projectView = QTableView()
projectView.setModel(projectModel)
projectView.show()
#db.close()
#db.removeDatabase('QODBC')
else:
QMessageBox.warning(None, "Info", "Error")
else:
QMessageBox.warning(None, "Info", "Error")