I am trying to fetch one value from a database using pymysql. My current solution is 3 lines of code. Is this the best way to handle this?
import pymysql
conn = pymysql.connect(host='localhost', user='root', passwd='')
conn.autocommit(True)
cur = conn.cursor()
memory = '100'
# I want to access one item from mySQL
cur.execute("""SELECT id FROM scada.sensors WHERE memory='{}'""".format(memory))
for x in cur.fetchall(): # only runs once
sensor_id=x[0]
Do I need this for loop to access the contents of cur.fetchall()?
I am using Python 3.2.3
If you are only interested in one value (or the first value), you can just use the
fetchonemethod in place offetchall. Here’s an example from the docs for MySQLdb (pymysql says it copies the entire MySQLdb API).