12

I've been learning Python recently and have learned how to connect to the database and retrieve data from a database using MYSQLdb. However, all the examples show how to get multiple rows of data. I want to know how to retrieve only one row of data.

This is my current method.

cur.execute("SELECT number, name FROM myTable WHERE id='" + id + "'")
results = cur.fetchall()
number = 0
name = ""
for result in results:
    number = result['number']
    name = result['name']

It seems redundant to do for result in results: since I know there is only going to be one result.

How can I just get one row of data without using the for loop?

2 Answers 2

17

.fetchone() to the rescue:

result = cur.fetchone()
Sign up to request clarification or add additional context in comments.

Comments

1

use .pop()

if results:
   result = results.pop() 
   number = result['number']
   name = result['name']

2 Comments

What if the cur.execute() didn't return any results? How would results.pop() behave?
@GaryJohnson put them inside a if to check if results if empty or not.

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.