如何在 PostgreSQL psycopg2 Python execute 语句中添加 Where 子句

How to add the Where clause in PostgreSQL psycopg2 Python execute statement

我正在尝试查询 return 一个值,但我得到 None!

        selectstatement = "SELECT * FROM customer Where (('ID' =" +"%s"
        data = 12345

        cursor.execute(selectstatement, (data,))
        records = cursor.fetchone()
        print(records[0])

现在我知道它存在于 table 但我收到错误:

Traceback (most recent call last):
  File "C:\Users\yfevrier\Desktop\EnterRegister.py", line 86, in <module>
    StartClean()
  File "C:\Users\yfevrier\Desktop\EnterRegister.py", line 28, in StartClean
    Analyze(DataReader)
  File "C:\Users\yfevrier\Desktop\EnterRegister.py", line 66, in Analyze
    print(records[0])
TypeError: 'NoneType' object is not subscriptable

如果我这样做:

selectstatement = "SELECT * FROM customer


cursor.execute(selectstatement)
records = cursor.fetchall()

我得到了所有结果,但我找不到完美指定 where 子句的资源。

您正在将字符串 ID 与传递的值进行比较。这是正确的方法:

selectstatement = "SELECT * FROM customer Where ID = %s"

但是如果 ID 列名是以大写字母创建并用双引号引起来的,则必须始终使用双引号:

selectstatement = '''SELECT * FROM customer Where "ID" = %s'''