immrsteel
immrsteel

Reputation: 1495

How to create table and insert data using MySQL and Flask

I am trying to insert data into a MySQL table. I'm able to connect to the database but when trying to insert data it is giving internal server error.

from flask import Flask
from flaskext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'test'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

@app.route("/")
def create_table():
    cursor = mysql.get_db().cursor()
    query = "CREATE TABLE potlala (id INT NOT NULL PRIMARY KEY, name  VARCHAR(40), email VARCHAR(40))"
    query = "INSERT INTO pot13 (id, name, email) VALUES ('2222', 'Maria',  '[email protected]')"
    cursor.execute(query)
    return "123"

if __name__ == "__main__":
    app.run()

Upvotes: 1

Views: 13302

Answers (2)

CompCy
CompCy

Reputation: 51

There are two things that you should do:

  1. Execute your queries separately.
  2. Commit (or rollback) your changes using the sql connection.
connection = mysql.get_db()
cursor = connection.cursor()
query = "CREATE TABLE potlala (id INT NOT NULL PRIMARY KEY, name  VARCHAR(40), email VARCHAR(40))"
cursor.execute(query)
query = "INSERT INTO pot13 (id, name, email) VALUES ('2222', 'Maria',  '[email protected]')"
cursor.execute(query)
connection.commit()

Upvotes: 5

davidism
davidism

Reputation: 127210

You set query to a create table statement, but never execute it before setting it to an insert statement and trying to execute that. The table doesn't exist, so the insert fails. Execute the first query first.

query = "CREATE TABLE ..."
cursor.execute(query)
query = "INSERT INTO ..."
cursor.execute(query)

Upvotes: 5

Related Questions