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
Tuberminator

Tuberminator

The main focus of this report is to show how to get involved in video marketing on the run, how to rank quickly on YouTube and Google using FREE semi-automatic tools and services. QUICKLY AND FREE. I will show methods and techniques I use to rank my videos, as well as free resources and tools to make video clips, to get backlinks and free traffic.

Get My Free Ebook


Post a comment