1

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

1 Answer 1

5

If you are only interested in one value (or the first value), you can just use the fetchone method in place of fetchall. Here's an example from the docs for MySQLdb (pymysql says it copies the entire MySQLdb API).

Sign up to request clarification or add additional context in comments.

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.