【问题标题】:Converting a tuple into an integer in python 3?在python 3中将元组转换为整数?
【发布时间】:2014-10-26 03:24:46
【问题描述】:

我有一个带有单个值的元组,它是数据库查询的结果(它给了我当前在数据库中的最大 ID #)。我需要将值加 1 以用于我的后续查询以创建与下一个 ID # 关联的新配置文件。

无法将元组转换为整数以便我可以加 1(在此处尝试迂回方式,将值转换为字符串,然后转换为 int)。请帮忙。

sql = """
SELECT id
FROM profiles
ORDER BY id DESC
LIMIT 1
"""

cursor.execute(sql)
results = cursor.fetchall()
maxID = int(','.join(str(results)))
newID = maxID + 1

【问题讨论】:

  • 要获取单元素元组的第一个(仅限 AKA)元素,请执行 mytuple[0] ;)

标签: python int tuples


【解决方案1】:

如果您只期望一行,则使用 cursor.fetchone() 而不是 fetchall() 并简单地索引到该方法返回的一行:

cursor.execute(sql)
row = cursor.fetchone()
newID = row[0] + 1

您可以直接向数据库询问最大值,而不是使用ORDER BY

sql = """SELECT MAX(id) FROM profiles"""

【讨论】:

    猜你喜欢
    • 2021-11-23
    • 2012-04-21
    • 2016-01-25
    • 1970-01-01
    • 2020-10-03
    • 2012-10-09
    • 2015-08-23
    • 2012-03-15
    • 2020-10-25
    相关资源
    最近更新 更多