PyQt, Python

Connecting to MySQL using PyQt

The first thing to do in getting the database connection to your application is to install sql drivers for python. To do this you’ll need to do the following:

# sudo apt-get install python-qt4-sql

This should install the necessary libraries. To test it (which is also a demonstration of how database connections in applications are made) you’ll need to do this;

Open Python Console

# python

>>> from PyQt4.QtSql import *

>>> db = QSqlDatabase.addDatabase(“QMYSQL”)

>>> db.setDatabaseName(“information_schema”)

>>> db.setUserName(“root”)

>>> db.setPassword(“obama”)



>>> query = QSqlQuery();

>>> query.exec_(“SELECT COUNT(*) FROM TABLES;”);




>>> query.value(0).toInt();

(205, True)

You can try out a more complex query using your own database. This is not necessarily the best method just a little overview on how to do it.