5

I am wondering how to fetch more than 1 column at the same time. This is the code I have so far but iI get the error: ValueError: too many values to unpack (expected 2)

con = sqlite3.connect('database.db')
cur = con.cursor()
cur.execute("SELECT name, age FROM employees")
name, age = cur.fetchall()

Is it actually possible to fetch more than 1 column at the same time? Thanks!

1
  • fetachall returns a list of each row as tuples, it doesn't return a tuple hence the error Commented Jul 12, 2018 at 13:29

1 Answer 1

5

cur.fetchall() gives you a list of (name, age) tuples, as many as there are rows in your employees table. Your contains more than just two rows, so your name, age = ... syntax fails because that requires there to be two results. Even if there are only two rows, you'd assign those two rows (each a tuple) to the names name and age which is probably not what you wanted.

You probably want to iterate over the cursor; this lets you process each row tuple separately, including assigning the two column values to two separate targets:

for name, age in cur:
    # process each name and age separately

or just assign the cur.fetchall() result to a single variable:

results = cur.fetchall()

and process the list as needed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.