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?

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.

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.

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

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.