[PyQt] Creating a table in a sqlite db using QtSql

Chris Wood c.c.wood at gmail.com
Wed Dec 3 16:50:18 GMT 2014


I’m attempting to create a sqlite database using the QtSql module. I
ensure that the database doesn’t already exist, and then create a
table. However, I get an error message: 'table People already exists
Unable to fetch row' - how can it already exist when I’m creating the
db in the previous line of code? It even happens when I explicitly try
and delete the table in advance. Full code is:

from PyQt4.QtSql import *
import os

print os.listdir(".")
database = QSqlDatabase.addDatabase("QSQLITE")
database.setDatabaseName("mynewdb.sqlite")
database.open()
sql = QSqlQuery("DROP TABLE IF EXISTS People")
a = QSqlQuery.exec_(sql)
print a
print sql.lastError().text()
sql = QSqlQuery("CREATE TABLE People (id integer primary key
autoincrement, name varchar(255))")
a = QSqlQuery.exec_(sql)
print a
print sql.lastError().text()

and output is:

[chris at chris dbdev]$ python test.py
[]
True

False
table People already exists Unable to fetch row

Just for my sanity, I checked it worked manually, and it does:

[chris at chris dbdev]$ ls
[chris at chris dbdev]$
[chris at chris dbdev]$ sqlite3
SQLite version 3.8.7 2014-10-17 11:24:17
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite> .open mynewdb.sqlite
sqlite> .tables
sqlite>
sqlite> create table People(id integer primary key autoincrement, name
varchar(255));
sqlite> .tables
People
sqlite> drop table People;
sqlite>
sqlite> .tables
sqlite>
sqlite> create table People(id integer primary key autoincrement, name
varchar(255));
sqlite> .tables
People

Any hints as to what I’m doing wrong?!

Cheers,
Chris


More information about the PyQt mailing list