简体   繁体   中英

Select specific column from specific row (Python - MySQL)

So I'm not so experienced in Python, but I really enjoy making stuff with it. I decided to start using Python to interact with MySQL in one of my projects.

I would like to write a function that takes the username as input and returns the password as output.

Here is what I've tried to do:

def get_passwd(user_name):
    user_passwd = mycursor.execute("SELECT passwd FROM users WHERE name = '%s'", (user_name))
    print(user_passwd)

get_passwd("Jacob")

But it's justing printing out "None".

My table looks like this:

It is unclear which package you are using to access your database. Assuming it is sqlalchemy what you are missing is the fetch command.

So you should add -

def get_passwd(user_name):
    user_passwd = mycursor.execute("SELECT passwd FROM users WHERE name = '%s'", (user_name))
    user_actual_passwd = user_passwd.fetchone()
    print(user_actual_passwd)
get_passwd("Jacob")

See more here

** Update as the question was updated **

I would make sure that the query strings is what you are expecting. Do -

query = "SELECT passwd FROM users WHERE name = '%s'", (user_name)
print (query)

If the query is what you are expecting, try running it directly on the db and see if you get any result.

Instead of

user_passwd = mycursor.execute("SELECT passwd FROM users WHERE name = '%s'", (user_name))

use something as

mycursor.execute("SELECT passwd FROM users WHERE name = '%s'", (user_name))
row = mycursor.fetchone()

user_passwd = row[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM