将从 PostgreSQL 获取的列表的数据类型从 NoneType 更改为 int

Change datatype of list fetched from PostgreSQL from NoneType to int

我尝试遍历从 PostgreSQL 的数据库中获取的数据。但是,我的数据是包含 Nonetype 对象的元组列表,因此我无法将它与 > 4 进行比较。

import psycopg2

# connect to an existing database
conn = psycopg2.connect(dbname='masterarbeit', user='postgres', password='####', port=5432)
cur = conn.cursor()

sql = "select min(id), max(id) from bsd_horizonte;"
cur.execute(sql)
gidsextent = cur.fetchall()
minimum = gidsextent[0][0]
maximum = gidsextent[0][1]


for gid in range(minimum,maximum+1):
    weizenausschluss = False
    sql = "select grobbod_k, boart from bsd_horizonte where id = " + str(gid) + ";"
    cur.execute(sql)
    data = cur.fetchall()
    if len(data) > 0:
        steine = data[0][0]
        boden = data[0][1]
        if steine > 4:
            weizenausschluss = True
        if boden == "Ss" or boden == "Su" or boden == "Tt":
            weizenausschluss = True
        if weizenausschluss == False:
            sql = "update bsd_horizonte set weizen_ok = True where id = " + str(gid) + ";"
            cur.execute(sql)
            conn.commit()
        else:
            sql = "update bsd_horizonte set weizen_ok = False where id = " + str(gid) + ";"
            cur.execute(sql)
            conn.commit()
    print(gid)
        
# Close communication with the database
conn.commit()
cur.close()
conn.close()

我收到以下错误:

Traceback (most recent call last):

  File "C:\Users\lucas\Desktop\Master Thesis\Python\Code\Code Bitterich\A06 wheat_horizon_ok.py", line 32, in <module>
    if steine > 4:

TypeError: '>' not supported between instances of 'NoneType' and 'int'

如何将 steine 的数据类型更改为 int,将 boden 的数据类型更改为 string? 谢谢!

如果 steine/bodenNone,您可以使用逻辑 or 来设置 'default' 值:

>>> data = [[None, None]]
>>> steine = data[0][0] or -1
>>> boden = data[0][1] or ''
>>> steine > 4
False

或者,更改您的 if 条件:

>>> data = [[None, None]]
>>> steine = data[0][0]
>>> if steine and steine > 4:
...     weizenausschluss = True

或更改您的 SQL,使用 COALESCE:

sql = "select COALESCE(grobbod_k, 0), COALESCE(boart, '') from bsd_horizonte where id = " + str(gid) + ";"

所以 Postgres 应该使用 0empty string 以防列值为 null.