问题
Is there an elegant way of getting a single result from an SQLite SELECT query when using python 2.7?
for example:
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
is there a way to avoid those nested for
s and get the value directly? I've tried
maxVal = cursor[0][0]
without any success.
回答1:
I think you're looking for Cursor.fetchone() :
cursor.fetchone()[0]
回答2:
Or you could write a wrapper function that, given SQL, returns a scalar result:
def get_scalar_result(conn, sql):
cursor=conn.cursor()
cursor.execute(sql)
return cursor.fetchone()[0]
I apologize for the possibly less than syntactically correct Python above, but I hope you get the idea.
回答3:
If you're not using pysqlite which has the built in cursor.fetchone
cursor.execute("select value from table order by value desc limit 1")
回答4:
select count(*) from ... groupy by ...
returns None
instead of 0
,
so fetchone()[0]
would lead to an exception.
Therefore
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
回答5:
or you can try :
cursor.execute("SELECT * FROM table where name='martin'")
来源:https://stackoverflow.com/questions/7011291/how-to-get-a-single-result-from-a-sqlite-query-in-python