SQLite python - 将值转换为变量

Posted

技术标签:

【中文标题】SQLite python - 将值转换为变量【英文标题】:SQLite python - Convert value into variable 【发布时间】:2022-01-01 00:09:59 【问题描述】:

我有一个表格,其中有一列包含不同的数字。所以看起来像

Name Number
John 22
Max 28
Debbie 22
John 21
John 52

如何将数字列相加并将其返回给变量

我现在所拥有的,将与名称匹配的每一行的数字,但它会像这样返回它:[(22),(21),(52)]

理想情况下,我希望能够使用 select 进行搜索,并将总计返回到 int 变量中。

  def get_num():
            with conn:
                c.execute("SELECT Number FROM table WHERE name=John")
                x = (c.fetchall())

                return x

        print(get_num())

【问题讨论】:

【参考方案1】:

使用 SQL SUM 函数。

c.execute("SELECT SUM(Number) FROM table WHERE name='John'")
return c.fetchone()[0]

【讨论】:

以上是关于SQLite python - 将值转换为变量的主要内容,如果未能解决你的问题,请参考以下文章