尝试返回列表而不是NoneType

时间:2018-07-09 10:24:51

标签: python python-3.x pymysql

我有一个函数,该函数调用数据库以获取特定用户的业务信息。我运行它,它返回一个格式如下的对象:

(614, 10, 503, '', '', '', '', '', 'null', None, None, None, None, None, '', 'F&B', 'Other', None, None, None, None, None, None, None, datetime.datetime(2018, 4, 4, 17, 46, 18), None, datetime.datetime(2018, 4, 18, 17, 46, 17), None, 0, None, None, None, 1, 0, None, None)

-

当我得到值时,我将其附加到列表中。整个列表都采用这种格式

(val1, val2, val3) (val1, val2, val3)......

因此,在这种情况下,我的问题是,我需要选择特定的值来对其进行验证,但由于得到的NoneType list而无法实现

全功能:

def check_subscription(ids):
    count = 0
    length = len(ids)-1
    all_businesses = []
    paid_user = []
    while count <= length:
        q = "SELECT * FROM TABLE_NAME where user_id = "+ str(ids[count])
        data = db.connect_once(q)
        all_businesses.append(data)

        count += 1
        #26
    count = 0
    while count <= (len(all_businesses)-1):
        print (all_businesses[count])
        count += 1

数据库功能:

def connect_once(q):
# Open database connection
db = pymysql.connect("CONNECTION DETAILS" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute(q)
data = cursor.fetchone()
#print (data)

# disconnect from server
db.close()
return data

所以我需要回答的问题如下:

1-我可以将返回值的类型/种类从NoneType更改为List吗?我的代码有误吗?

谢谢

1 个答案:

答案 0 :(得分:1)

简单的解决方案是添加一个检查,以通过测试connect_once是否返回cursor.fetchone()来确保在运行None时存在数据。您可以将其作为connect_once方法的一部分:

def connect_once(q):
...
# execute SQL query using execute() method.
cursor.execute(q)
data = cursor.fetchone()
if data == None:
    # do something, e.g. throw an error, set 'data' to be an empty list, etc.
db.close()
return data

或作为check_subscription的一部分:

def check_subscription(ids):
    ...
    while count <= length:
        q = "SELECT * FROM TABLE_NAME where user_id = "+ str(ids[count])
        data = db.connect_once(q)
        if data == None:
             # throw an error or whatever
        else:
            all_businesses.append(data)
        count += 1
    count = 0

    while count <= (len(all_businesses)-1):
        print (all_businesses[count])
        count += 1

您可以根据脚本的需求来决定采取适当的措施(引发错误,忽略结果并继续执行等)。