QtSql in PyQt4 - handling databases
Check out the new site at https://rkblog.dev.
12 December 2008
Comments
In Qt/PyQt4 we have access to QtSql classes, that offer database handling classes (SQL execution, grids and more). However on Windows default PyQt4 package supports only SQLite and ODBC (PyQt4/Qt4 recompilation would be required to support other databases). If you need only SQL support - you can use standard Python libraries for your database.
Here is a basic QtSql usage - connecting and executing SQL query:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
app = QApplication(sys.argv)
w = QTextBrowser()
# DB type, host, user, password...
db = QSqlDatabase.addDatabase("QMYSQL");
db.setHostName("localhost")
db.setDatabaseName("test")
db.setUserName("root")
db.setPassword("")
ok = db.open()
# True if connected
if ok:
w.insertHtml('Connected to MySQL<br />')
else:
w.insertHtml('ERROR connecting to MySQL<br />')
# do a query "on" a DB connection
query = QSqlQuery(db)
if query.exec_("SHOW TABLES"):
w.insertHtml('<br />')
while query.next():
table = query.value(0).toString()
w.insertHtml('%s<br />' % table)
w.insertHtml('<br />')
w.insertHtml('TOTAL %s TABLES' % query.size())
w.show()
sys.exit(app.exec_())
RkBlog
Check out the new site at https://rkblog.dev.
Comment article