Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中从SQL查询中获得单个结果?_Python_Sql_Sqlite - Fatal编程技术网

如何在python中从SQL查询中获得单个结果?

如何在python中从SQL查询中获得单个结果?,python,sql,sqlite,Python,Sql,Sqlite,在使用Python时,有没有一种优雅的方法可以从SQLite SELECT查询中获得单个结果 例如: conn = sqlite3.connect('db_path.db') cursor=conn.cursor() cursor.execute("SELECT MAX(value) FROM table") for row in cursor: for elem in row: maxVal = elem 有没有办法避免嵌套的fors并直接获取值

在使用Python时,有没有一种优雅的方法可以从SQLite SELECT查询中获得单个结果

例如:

conn = sqlite3.connect('db_path.db')
cursor=conn.cursor()
cursor.execute("SELECT MAX(value) FROM table")

for row in cursor:
    for elem in row:
        maxVal = elem
有没有办法避免嵌套的
for
s并直接获取值?我试过了

maxVal = cursor[0][0]

没有任何成功。

我想你在寻找:

或者您可以尝试:
cursor.execute(“SELECT*FROM table where name='martin'”)

或者您可以编写一个包装函数,在给定SQL的情况下,该函数返回一个标量结果:

def get_scalar_result(conn, sql):
    cursor=conn.cursor()
    cursor.execute(sql)

    return cursor.fetchone()[0]

很抱歉上面的Python语法可能不太正确,但我希望您能理解。

如果您没有使用内置
游标的pysqlite.fetchone

cursor.execute("select value from table order by value desc limit 1")
从中选择计数(*)。。。groupy by…
返回
None
而不是
0
, 因此,
fetchone()[0]
将导致异常

所以

def get_scalar_from_sql(sqlcur, sqlcmd):
    # select count(*) from .... groupy by ... returns None instead of 0
    sqlcur.execute(sqlcmd)
    scalar = 0
    tuple_or_None = sqlcur.fetchone()
    if not tuple_or_None is None:
        (scalar,) = tuple_or_None
    return scalar
可用于从结果元组中提取标量值

如果有多行,则通过迭代光标(或
cursor.fetchall
):

for result, in cursor:
    print(result)
或者如果结果集中只有一行,则使用
cursor.fetchone

result, = cur.fetchone()
print(result)
在这两种情况下,
result
后面的逗号从单元素元组中解压元素。这与更常见的情况相同

a, b = (1, 2)
除了元组之外,元组只有一个元素:

a, = (1,)
a, = (1,)