1

I have a table, and I want to execute a query that will return the values of two rows:

 cursor.execute("""SELECT `egg_id`
 FROM `groups`
 WHERE `id` = %s;""", (req_id))
 req_egg = str(cursor.fetchone())
 print req_egg

The column egg_id has two rows it can return for that query, however the above code will only print the first result -- I want it to also show the second, how would I get both values?

Edit: Would there be any way to store each one in a separate variable, with fetchmany?

asked Apr 28, 2012 at 9:37

3 Answers 3

5

in this case you can use fetchmany to fetch a specified number of rows:

req_egg = cursor.fetchmany(2)

edit:

but be aware: if you have a table with many rows but only need two, then you should also use a LIMIT in your sql query, otherwise all rows are returned from the database, but only two are used by your program.

answered Apr 28, 2012 at 9:46
Sign up to request clarification or add additional context in comments.

Comments

1

Call .fetchone() a second time, and it would return the next result.

Otherwise if you are 100% positively sure that your query would always return exactly two results, even if you've had a bug or inconsistent data in the database, then just do a .fetchall() and capture both results.

answered Apr 28, 2012 at 9:44

Comments

1

Try this:

Cursor.fetchmany(size=2)

Documentation for sqlite3 (which also implements dbapi): http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.fetchmany

answered Apr 28, 2012 at 9:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.