0

I want to get a value from a database table using python. I am sending a query and getting value like this:

conn = pymysql.connect(rds_host, user=name, passwd=password,db=db_name, connect_timeout=10)
with conn.cursor() as cur:
    cur.execute("SELECT id FROM user_details WHERE email='{}'".format(email)
    for row in cur:
        id = row[0]

Is there a way to get the value without using for loop.

1
  • How many values do you expect to get? If just one, you can use id_=next(cur)[0]. As a side note, do not call your variables id. Commented Feb 19, 2018 at 8:19

1 Answer 1

2

Couldn't find the doc ?

https://pymysql.readthedocs.io/en/latest/modules/cursors.html#pymysql.cursors.Cursor.fetchone

cursor.fetchone()

Fetch the next row

Also, you definitly DONT want to use string formatting to build your queries (unless you're ok to have your app wide opened to sql injections of couse). You want to use prepared queries instead:

cur.execute("SELECT id FROM user_details WHERE email=?", [email,])
Sign up to request clarification or add additional context in comments.

1 Comment

To get a single value, it should be a = cursor.fetchone(); new_id = a[0];

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.