从 flask 中的 mysql php 获取行的值 python

Get value of row from mysqlphp in flask python

我 table 喜欢: Database

我只想像这样打印密码:

samer

我试过这个:

mysql = MySQL()
flask.config['MYSQL_HOST'] = 'localhost'
flask.config['MYSQL_USER'] = 'root'
flask.config['MYSQL_PASSWORD'] = ''
flask.config['MYSQL_DB'] = 'web'
mysql.init_app(flask)

@flask.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
    email = request.form['email']
    password = request.form['password']
    # print(password)
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cur.execute('SELECT * FROM users WHERE password=%s', (password,))
    user = cur.fetchall()
    print(user)
    # if password is wrong, user will be None else Dict
    if user is not None:
        print(user['password'])
    else:
        print("User not found")

但我得到这个错误:

TypeError: 元组索引必须是整数或切片,而不是 str

我可以打印结果如果我使用:

for row in user:
    passw = row['password']

但我需要使用第一种方法,我该如何实现?

您需要将 fetchall 调用替换为 fetchone:

 cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
 cur.execute('SELECT * FROM users WHERE password=%s', (password,))
 user = cur.fetchone()
 # if password is wrong, user will be None else Dict
 if user is not None:
     print(user['password'])
 else:
     print("User not found")