2011-08-10 113 views
24

當使用python 2.7時,是否有從SQLite SELECT查詢中獲得單個結果的優雅方式?如何從python中的SQLite查詢中獲取單個結果?

例如:

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] 

沒有任何成功。

回答

-2

,或者你可以嘗試: cursor.execute("SELECT * FROM table where name='martin'")

3

或者你可以寫一個包裝函數,考慮到SQL,返回標結果:

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

    return cursor.fetchone()[0] 

我對上面可能不太符合語法正確的Python表示歉意,但我希望你明白。

1

如果你不使用pysqlite已經內置在cursor.fetchone

cursor.execute("select value from table order by value desc limit 1") 
相關問題