[PyQt] QMYSQL + QSqlQueryModel.

Igor Prischepoff igor at tyumbit.ru
Tue Sep 22 08:14:48 BST 2009


Hello, I'm recently upgraded my python setup to
python 2.6.2 + Qt 4.5.1 + latest pyqt (on WinXP)

I'm trying to work with mysql through qmysql plugin & QtSql.QSqlQueryModel
here is code demonstrating my problem:
--------------
from PyQt4 import QtSql, QtGui,QtCore
import sys

views = []
def initializeModel(model):
    model.setQuery("select user.user from user")
    model.setHeaderData(0, QtCore.Qt.Horizontal,
QtCore.QVariant(QtCore.QObject.tr(model, "user")))

def createView(title, model):
    view = QtGui.QTableView()
    views.append(view)
    view.setModel(model)
    view.setWindowTitle(title)
    view.show()
def createConnection():
    db = QtSql.QSqlDatabase.addDatabase("QMYSQL")
    db.setHostName('localhost')
    db.setDatabaseName("mysql")
    db.setUserName("root")
    db.setPassword("root")

    if not db.open():
        QtGui.QMessageBox.critical(None, QtGui.qApp.tr("Cannot open
database"),
                QtGui.qApp.tr("Unable to establish a database
connection.\nClick Cancel to exit."),
                QtGui.QMessageBox.Cancel)
        return False
    return True

class CustomSqlModel(QtSql.QSqlQueryModel):
    def data(self, index, role):
        value = QtSql.QSqlQueryModel.data(self, index, role)

        if value.isValid() != True:
            print 'value not valid?'
        else:
            print "value ok"
        return value
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    #
QtCore.QTextCodec.setCodecForLocale(QtCore.QTextCodec.codecForName("cp1251")
)
    #
QtCore.QTextCodec.setCodecForCStrings(QtCore.QTextCodec.codecForName("cp1251
"))
    #
QtCore.QTextCodec.setCodecForTr(QtCore.QTextCodec.codecForName("cp1251"))

    if not createConnection():
        sys.exit(1)

    CustomModel = CustomSqlModel()

    initializeModel(CustomModel)

    createView(QtCore.QObject.tr(CustomModel, "Custom Query Model"),
CustomModel)

    app.setQuitOnLastWindowClosed(True)
    sys.exit(app.exec_())
----------
generally it's trying to show all logins available in mysql database.
Please see,that it's system database.

What I've got on the screen is a table with 4 EMPTY rows (no logins
displayed) and output on console: 'value not valid?' many times...

c\:mysql -V
C:\Program Files\MySQL\MySQL Server 5.0\bin\mysql.EXE  Ver 14.12 Distrib
5.0.45, for Win32 (ia32)

c:\> mysql -uroot -proot -Dmysql -e"select user.user from user"  shows
that's there is actually some logins
+------+
| user |
+------+
| igor |
| root |
| igor |
| root |
+------+

Could please someone check my script on his own mysql db?
Is something wrong with decoding/encoding my values which I receive from db?
or with mysql setup? 
or with mysql plugin which comes with pyqt installation?





---

igor at tyumbit.ru



More information about the PyQt mailing list