37

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 を回避して値を直接取得する方法はありますか? 私はもう試した

maxVal = cursor[0][0]

成功せずに。

4

7 に答える 7

77

Cursor.fetchone()を探していると思います:

cursor.fetchone()[0]
于 2011-08-10T13:11:58.890 に答える
7

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.

于 2011-08-10T13:37:51.577 に答える
3

組み込みのpysqliteを使用していない場合cursor.fetchone

cursor.execute("select value from table order by value desc limit 1")
于 2014-12-05T23:46:23.300 に答える
-4

または試すことができます: cursor.execute("SELECT * FROM table where name='martin'")

于 2011-08-10T13:22:05.213 に答える