Can't insert from flask application to MySQL database?

Viewed 148

I have been trying to insert a username name and password from my flask webpage into a mysql database. Here is my code for inserting into my mysql database.

name = request.form['name']
username = request.form['username'] 
cursor = db.connection.cursor(MySQLdb.cursors.DictCursor) 
cursor.execute( "SELECT * FROM accounts WHERE username = %s", [username])
account = cursor.fetchone()
 if account:
     flash("Account already exists!", "danger")
 else:     
     password = request.form['password']
     pw_hash = bcrypt.generate_password_hash(password)
     sql = ("INSERT INTO users (username, name, password) VALUES( %s, %s, 
     %s)")
     data = (username, name, pw_hash)
     cursor.execute(sql, data)
     cursor.commit()

I have checked the database connection and the connection is fine. I have also checked that the user of the database has the right privileges. I am using MySQLdb.cursors as the database api to interact with mysql and flask_mysqldb. When I run the app, there are no errors raised by the debugger. My application can read from the database for login but can't insert into a database.

1 Answers

I highly recommend you use an ORM for flask <-> database interactions. It's much more secure and efficient. You should try SQLAlchemy. It will take some time to get used to it, but it will justify all efforts. Using raw SQL in code is also a weak practice. But if we take the code for granted, can you read the MySQL db response after you execute INSERT? I see that you store the hash but the db column name is 'password'. Is that ok?

Related