Connecting to the Database

But before we can do any work with a database, we must establish a connection to it. In many database applications this is done after the creation of the QApplication object, but before the main form is created or shown. Other applications establish their connections later on—for example, only when they are needed.

To use PyQt's SQL classes we must import the QtSql module:

from PyQt4.QtSql import *

A database connection is established by calling the static QSqlDatabase.addData-base() method, with the name of the driver we want to use. Then we must set various attributes, such as the database's name, the username, and the password. And finally, we must call open() to make the connection.

db = QSqlDatabase.addDatabase("QSQLITE")

db.setDatabaseName(filename)

QMessageBox.warning(None, "Phone Log",

QString("Database Error: %1").arg(db.lastError().text())) sys.exit(1)

For SQLite we need to specify only the name of the database. This is normally a filename, but it can be the special name ":memory:" for an in-memory database. When we call QSqlDatabase.open() using the SQLite driver, if the file does not exist it will be created, in which case it will have no tables or records.

Notice that we have passed None as the message box's parent: This is because we have tried to establish the connection before creating the main window, so there is no possible parent. Since this application depends on the database, if no connection can be made it simply tells the user the error message that was received and terminates the application.

If the database connection was successfully opened, from now on all database methods will apply to this connection. If we need two or more separate connections, whether to the same database or to different databases, we must pass a second argument to addDatabase(), giving the connection a name that we can then use to distinguish between our different connections.

Was this article helpful?

+1 0
Tube Jacker

Tube Jacker

Download Tube Jacker And Discover Everything You Need To Know About Jacking Unlimited Traffic From The Video Giant. The drop dead easy way to create winning video campaigns that will FLOOD your website with unstoppable FREE traffic, all on complete and total autopilot. How to exploit a sneaky method of boosting exposure and getting your videos to the top of Google within 72 hours, guaranteed.

Get My Free Ebook


Post a comment