PDA

View Full Version : Issue with query.exec_ in PyQt5



Evethir
8th January 2018, 16:58
I folks!
I'm new in the Qt and PyQt world, more precisely in the latter! At the moment I'm using PyQt 5.6 with Python 3.5 and i'mtrying to connect my simple app to a local MySQL server. I managed to open the server, but unfortunately the program crash whenever I commit a query (Which i'm sure it's correct since it works fine on SQLyog).
My code is the following:

from PyQt5 import QtWidgets, QtSql
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QApplication

import sys

app = QApplication(sys.argv)
db = QtSql.QSqlDatabase.addDatabase("QMYSQL")
db.setHostName("localhost")
db.setUserName("root")
db.setPort(3306)
db.setDatabaseName("users")
db.setPassword("")

db.open()
if db.open():
print("Db open!")
query = QtSql.QSqlQuery(db)

query.exec_("SELECT * FROM userscredentials")

print(query.value(0))

else:
print("Db not open")


input("")

sys.exit(app.exec_())

and i got the following output


C:\Python35\python.exe C:/Users/Egon/PycharmProjects/PyQt/DemoSQL/mainFIle.py
Db open!

Process finished with exit code -1073741819 (0xC0000005)

Can you please help me to understand the problem ?

d_stranz
9th January 2018, 03:39
0xC0000005

In the Microsoft world, this error code means the program crashed with an access violation. That means something in the program tried to use an invalid (probably NULL) pointer to read or write something.

The QSqlQuery::exec() method returns a bool code that tells you whether the query succeeded or not. You don't bother to check so you don't actually know if the query succeeded.. But even if it did succeed, the record cursor isn't pointing to a valid record until you call one of the record navigation functions (QSqlQuery::first(), QSqlQuery::next(), etc.). You haven't done that either, meaning query.value(0) isn't accessing a valid record and is probably returning a NULL pointer. When you send that NULL pointer to the print method, boom!

Note that the record navigation functions also return a bool indicating whether or not they succeeded, and you will be wise to check that value before you try to access the record in any way.

fifth
15th January 2018, 22:19
query = QtSql.QSqlQuery(db)

query.exec_("SELECT * FROM userscredentials")

print(query.value(0))


As above, your query is not pointing at a valid record. You don't call query.next() (or first as d_stranz said). If your expecting a single record you can do;


if query.next():
print(query.value(0))

or for more results use a while loop:


while query.next():
print(query.value(0))