Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select single item in MYSQLdb - Python

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?

like image 927
Gary Holiday Avatar asked Sep 15 '16 19:09

Gary Holiday


People also ask

How do you SELECT data from a database in Python?

You can fetch data from MYSQL using the fetch() method provided by the mysql-connector-python. The cursor. MySQLCursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples.

What is use of Fetchall () function?

fetchall() The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.

Which object is used to execute an SQL query in MYSQLdb in Python?

Next, db object is used to create a cursor object, which in turn is used to execute SQL queries.


1 Answers

.fetchone() to the rescue:

result = cur.fetchone()
like image 71
alecxe Avatar answered Oct 22 '22 23:10

alecxe