mn_wy
mn_wy

Reputation: 129

Fetch data from sqlite3 and save in list

I would like to fetch data from a sqlite3 database and save them in a list.

conn=sqlite3.connect("words.db")
cur=conn.cursor()
cur.execute("SELECT word FROM words WHERE state='positive'")
rows=cur.fetchall()
conn.commit()
conn.close()
print(rows)

The output of rows is this:

[('abound',), ('abounds',), ('abundance',)]

I would like to have:

['abound', 'abounds', 'abundance']

I created the db with this:

cur.execute("CREATE TABLE IF NOT EXISTS words (id INTEGER PRIMARY KEY, word TEXT, meta TEXT)")

Upvotes: 0

Views: 2271

Answers (1)

AKX
AKX

Reputation: 169338

Just take the first column of each returned row tuple.

rows = [r[0] for r in cur]

You don't need to commit after a select either.

Upvotes: 2

Related Questions