[PyQt] PyQt API 2: equivalent of Null QVariant?

TP paratribulations at free.fr
Tue Dec 21 10:05:03 GMT 2010


Hello,

I currently use the API 1, and use the isNull() method of QVariant to detect 
a Null QVariant. This is necessary to detect a NULL value in a database.

It seems there is no equivalent in API2 of PyQt. None is used to model an 
invalid QVariant. But how to model a Null QVariant?

http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#id13

Compare the output of the two following examples.

Thanks

Julien

########################
# Example 1: using API 1 for QVariant

from PyQt4.QtSql import *
import sys

db = QSqlDatabase.addDatabase( "QSQLITE" )
db.setDatabaseName( ":memory:" )

if not db.open():
    sys.exit(1)

query = QSqlQuery()

query.exec_( "CREATE TABLE person ( firstname VARCHAR(20)"
        ", lastname VARCHAR(20) );" )
query.exec_( "INSERT INTO person VALUES( 'Danny', 'Young');" )
query.exec_( "INSERT INTO person ( firstname ) VALUES( 'Christine' );" )
query.exec_( "INSERT INTO person VALUES( 'Lars', 'Gordon');" )

query.exec_( "SELECT * FROM person;" )

record = query.record()
for i in range( record.count() ):
    print record.fieldName( i ), "\t",

print "\n----------------------------"

for i in range( record.count() ):
    while query.next():
        for i in range( record.count() ):
            value = query.value(i)
            if value.isNull():
                print "NULL", "\t",
            else:
                print value.toString(), "\t",
        print

########################
# Example 2: using API 2 for QVariant

import sys, sip
sip.setapi('QVariant', 2)

from PyQt4.QtSql import *

db = QSqlDatabase.addDatabase( "QSQLITE" )
db.setDatabaseName( ":memory:" )

if not db.open():
    sys.exit(1)

query = QSqlQuery()

query.exec_( "CREATE TABLE person ( firstname VARCHAR(20)"
        ", lastname VARCHAR(20) );" )
query.exec_( "INSERT INTO person VALUES( 'Danny', 'Young');" )
query.exec_( "INSERT INTO person ( firstname ) VALUES( 'Christine' );" )
query.exec_( "INSERT INTO person VALUES( 'Lars', 'Gordon');" )

query.exec_( "SELECT * FROM person;" )

record = query.record()
for i in range( record.count() ):
    print record.fieldName( i ), "\t",

print "\n----------------------------"

for i in range( record.count() ):
    while query.next():
        for i in range( record.count() ):
            value = query.value(i)
            if value == None:
                print "NULL", "\t",
            else:
                print value, "\t",
        print






More information about the PyQt mailing list