0

I am trying to connect to postgresql with qt. I managed that last one, but, just like in my previous question, an invisible internal error occurs. The difference is that now it happens when a query fails (for example, when the table does not exist).

The program should print None to the screen. But the program ends before that. Exactly when I call obj.prepare(query).

This is my code:

from PySide2.QtSql import QSqlDatabase, QSqlQuery
from PySide2.QtWidgets import QApplication, QMainWindow

app = QApplication([])

class SqlError(Exception):
    pass

def connect(host, port, dbname, user, password):
    db = QSqlDatabase.addDatabase("QPSQL")
    db.setHostName(host)
    db.setPort(port)
    db.setDatabaseName(dbname)

    if(not db.open(user, password)):
        raise SqlError(db.lastError().text())

def execute(query, *args, **kwargs):
    obj = QSqlQuery()

    if(not obj.prepare(query)):
        raise SqlError(obj.lastError().text())
    
    if(kwargs):
        for var, value in kwargs.items():
            obj.bindValue(var, value)
    elif(args):
        for value in args:
            obj.addBindValue(value)

    if(not obj.exec_()):
        raise SqlError(obj.lastError().text())

connect(host="localhost",
        port=0,
        dbname="mydatabase",
        user="user",
        password="password")

print(execute("SELECT * FROM c_venta"))

Attached screenshot of my idle. This behavior is similar to what happens when running from cmd and importing my script from the interpreter.

enter image description here

What do I need to catch that error, what am I doing wrong? I've looked at several tutorials and I'm doing the same.

Edit: I tried the script importing it from the interpreter and it closes said interpreter without saying anything.

Edit 2: I tried variants of a certain answer and it didn't work for me either. https://stackoverflow.com/a/33741755/12913664

Edit 3: Pass the result of QSqlDatabase.database() to QSqlQuery (same result), to prepare (says it only accepts one argument), and tried saving the connection to a global variable and using db.exec (same result).

Dante S.
  • 222
  • 3
  • 16
  • What were you expecting the script to do? Why do you think there's an error? The `execute` function doesn't return anything, so there's nothing to print. – ekhumoro Nov 20 '22 at 21:56
  • @ehumoro I know. The print is more to test if it works. After getting it to work, I think about what the function should return. – Dante S. Nov 21 '22 at 01:16
  • Get **what** to work? What **specifically** do you think is not working? That print statement will literally print nothing, *even if everything else is working properly* - so it's not testing anything at all. – ekhumoro Nov 21 '22 at 12:10
  • Maybe there's a mixup or something, but in Python, if you do print(None), None is output to the screen. That is what should happen. But the program doesn't even do that. I'll clarify it up in an edit, sorry @ekhumoro – Dante S. Nov 21 '22 at 14:03
  • Can you try: 1. to catch the error you raise ([try ... except](https://docs.python.org/3/tutorial/errors.html#handling-exceptions)) and 2. to set an actual port when you connect? – Atmo Nov 21 '22 at 14:45
  • @atmo 1. I already tried, without success 2. The published port is an example. I didn't share the real one for safety. In the original code, I use a valid port. Thank you both in the same way c: – Dante S. Nov 21 '22 at 14:55
  • The problem is not in the raise. Python exits without saying anything before obj.prepare even returns anything. That's what my tests indicate. That's why I say, it seems to be an internal Qt bug. Maybe I'm doing something wrong? – Dante S. Nov 21 '22 at 14:57
  • Then my guess (from Qt C++) is that you forgot to pass your db connection to your query, i.e. `obj = QSqlQuery(QSqlDatabase.database())` – Atmo Nov 21 '22 at 15:01
  • @atmo It was not successful. See the end of the question. I don't know anything about C++, but maybe if those who understand it read that code, they can see if there are any internal errors. – Dante S. Nov 21 '22 at 15:09
  • Also, it seems that PySide2 has this behavior by default, but it's always good to try. – Dante S. Nov 21 '22 at 15:09
  • @DanteS. The script runs fine for me (and there's no obvious *programmatic* reason why it shouldn't). To test things further, I also deliberately added typos to the arguments of `connect` and `execute`, and each one produced the expected traceback. Running the script in a terminal *vs* idle, also makes no difference. I suggest you try systemmatically testing things as I did above until you find the specific line that causes the problem (whatever that's supposed to be). You should also carefully recheck your postgresql setup using the command-line `psql` utility. – ekhumoro Nov 21 '22 at 21:47
  • @DanteS. PS: and also ensure you install the most up to date versions of Python, PySide2, PostgreSql, etc that are available for your system. – ekhumoro Nov 21 '22 at 21:52
  • @ekhumoro I have well identified the line where the error occurs. What settings should I check exactly? And I tried upgrading to Python 3.10, since a higher version is not suitable, and the same error occurs. – Dante S. Nov 21 '22 at 23:18
  • @DanteS. Which specific line? What specific error? (And please don't say the print statement, which has no relevance). If you don't know how to set up a postgresql db properly, [please consult a tutorial](https://www.postgresqltutorial.com/postgresql-getting-started/connect-to-postgresql-database/). Once you've done that, start a `psql` interactive session and verify that you can create a table, insert records, and select some rows. Then use the script with the same connection/db/table info, and verify that every line **witihin** `connect` and `execute` works correctly. – ekhumoro Nov 22 '22 at 02:17
  • @ekhumoro The error is in obj.prepare(query), and what happens is that Python terminates its execution without reporting anything. Thanks for the recommendation, but my postgresql server is already configured, so I was wondering what configuration I could check. I have the permissions. Note that the failure only happens if the query is invalid in some way, such as a syntax error or a non-existent table. – Dante S. Nov 22 '22 at 12:33
  • @DanteS. What exact versions of Qt5 and PySide2 are you using? If there's a bug, it's most likely in PySide2, or maybe the Qt PostgreSql plugin. Try installing PyQt5 and/or PySide6, and run the same script with those. If the problem persists, it's probably an issue with the plugin on Windows (since I can't reproduce it on Linux). Set the envar QT_DEBUG_PLUGINS=1 and run the script in a command-window (i.e. not using idle). If that doesn't reveal anything, try modifying the script to use QSQLITE instead, and check whether prepare works properly with that. – ekhumoro Nov 22 '22 at 14:12
  • @ekhumoro The version of PySide2 is 5.15.2.1. I don't know how to find out the version of qt. The qt_debug_plugins thing doesn't reveal anything. And I have already tried with qsqlite and it works fine. I tried with pyside6 and pyqt5 and nothing. – Dante S. Nov 22 '22 at 14:35
  • What does "and nothing" mean? Are you saying that you can't reproduce the problem with pyside6 and pyqt5? If so, that strongly indicates a pyside2 bug, which means it's unlikely to be fixed now. You can report it on [the bug tracker](http://bugreports.qt.io/secure/Dashboard.jspa), but you'll probably be advised to use pyside6, since almost all development effort is focused on that now. – ekhumoro Nov 22 '22 at 14:50
  • Sorry if I misunderstood. What I mean is that I tried with PySide6 and PyQt5 and the same error occurs as with PySide2. Thanks for the advice and for all the attention. I appreciate it. Luckily, I can use another library to communicate with postgresql. So that's what I'll use for now. – Dante S. Nov 22 '22 at 14:54
  • By the way, can I ask you a little question on the side? (if I did it in the form of a publication, it would be based on opinions, so I ask you here). Which is more likely to stay up for a long time? PySide (with 32-bit compatibility) or PyQt? – Dante S. Nov 22 '22 at 14:56
  • So the bug is probably in the Windows version of the Qt PostgreSql plugin. If it can be reproduced in PySide6, it's worth reporting the issue on the tracker as that means it's much more likely to be fixed. – ekhumoro Nov 22 '22 at 14:58
  • I don't know what you mean by "stay up for a long time". – ekhumoro Nov 22 '22 at 15:00
  • Perfect! I will! Sorry, I mean continue to have support. – Dante S. Nov 22 '22 at 15:02
  • If you're using the open source versions, there will never be any guarantees. Qt5 long-term support only lasts up until May 2023, unless you have a developer licence, in which support ends in May 2025. – ekhumoro Nov 22 '22 at 22:26
  • @ekhumoro But I can update. What I mean is, which offers more guarantee (I know that the future is uncertain, that's why I say, that it is more likely) to stay updated. – Dante S. Nov 23 '22 at 14:43
  • You'd have to ask the current maintainers of the code about what is "more likely" - but I doubt whether their predictions would be significantly more accurate than anyone else's. Most open-source projects have a relatively small group of regular contributors. The project might have a long history of excellent support, but the past is not a reliable guide to the future. Even if you buy a licence, there are no guarantees. It's really up to you to make a judgement about which project you should commit to. – ekhumoro Nov 24 '22 at 13:31

0 Answers0