PyQt和Postgresql:在PSQL中工作的简单查询出现语法错误。

问题描述 投票:0回答:1

我相信这是非常简单的,但我无法使用QPSQL的PyQt5让这个基本查询工作。

import sys
from PyQt5.QtSql import *

class Main():

    def __init__(self, parent=None):
        SQL = "SELECT address FROM organisation_addresses WHERE organisation_id = ?"
        query = QSqlQuery()
        query.prepare(SQL)
        query.addBindValue(12)       
        query.exec_(SQL)
        query.first()

        if query.isActive():
                print(query.value("address"))
        else:
            print(query.lastError().text())

if __name__=="__main__":
    db = QSqlDatabase.addDatabase("QPSQL");
    db.setHostName(server)
    db.setDatabaseName(database)
    db.setUserName(user)
    db.setPassword(pword)
    if (db.open()==False):
        QMessageBox.critical(None, "Database Error", db.lastError().text())

    myapp = Main()

如果我把查询改为 "SELECT address FROM organisation_addresses WHERE organisation_id = 85",注释掉query.prepare和query.addBindValue,查询就能正常工作。 它似乎不喜欢我的"?"。当我在psql中运行查询时,它也能正确运行。

当我在Postgres上运行select version()时,我得到。

PostgreSQL 10.12 (Ubuntu 10.12-0ubuntu0.18.04.1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0, 64-bit

我已经在Linux Mint 19.3, Ubuntu 20.04和Windows 10上尝试了PyQt查询。 同样的结果。 有什么好办法吗?

python postgresql pyqt pyqt5
1个回答
0
投票

如果你要使用占位符,那么你不应该把查询传递给exec(),因为QSqlQuery已经有了语句,只能使用。

SQL = "SELECT address FROM organisation_addresses WHERE organisation_id = ?"
query = QSqlQuery()
query.prepare(SQL)
query.addBindValue(12)       
query.exec_()
query.first()

if query.isActive():
    print(query.value("address"))
else:
    print(query.lastError().text())
© www.soinside.com 2019 - 2024. All rights reserved.