如何在python中从SQL查询中获得单个结果?
在使用Python时,有没有一种优雅的方法可以从SQLite SELECT查询中获得单个结果 例如:如何在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并直接获取值
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,)