【问题标题】:What is the most elegant way to extract an value from a database从数据库中提取值的最优雅方法是什么
【发布时间】:2019-11-22 18:44:32
【问题描述】:

我正在尝试从 SQlite 数据库中获取值。我知道只有 那一个值。通过 SELECT 检索它时,它返回一个列表,其中还包含行的键。 我只想获取值,它是一个 int。

这个问题最优雅/最好的解决方案是什么?

我正在考虑通过 SELECT 获取列表,删除所有非数字字符并将其转换为 int。

返回值 (data = ) 是 [{'cash': 10000}]。我只想提取10000。

data base (example)

id || username || hash || cash
1 || user1 || xxx || 10000
2 || user2 || yyy || 5400

data = db.execute("SELECT cash FROM users WHERE id = :userid",userid=session.get("user_id"))
currentCash = str(data[0])
userCurrentCash = re.sub("[^0-9]","",currentCash)

【问题讨论】:

  • 您通常不会在光标对象上使用execute,然后使用fetchFOO 方法之一吗?
  • @Shawn 在使用游标对象和使用 fetchxx 方法时有何不同?

标签: python-3.x sqlite select


【解决方案1】:

由于data 返回[{'cash': 10000}]data[0]['cash'] 将返回10000。它将(自动)转换为整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 2020-01-16
    • 1970-01-01
    相关资源
    最近更新 更多