1

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()
5
  • 1
    Run the script from the command line and catch the error, print it and include it here. Also, have you tried using SQLAlchemy? Commented Jun 4, 2015 at 22:06
  • @john yeah I ran the script from the command line,no error pop up but when I localhost it gives me internal server error and One thing more when I'm changing "2222" to '1234' in query section ,it is giving me HTTP 200:OK but not inserting anything into database. Commented Jun 4, 2015 at 22:46
  • Encapsulate the block in try catch and catch the error. There will definitely be an output. Commented Jun 4, 2015 at 22:47
  • I'm completely new to this things,Will SQLAlchemy do the work of CRUD with mysql using python and flask? Commented Jun 4, 2015 at 22:48
  • It alleviates the need to write sql queries. Queries become: dbdefs.potlala.query.filter_by(patella_id = your_variable) Commented Jun 4, 2015 at 22:49

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

5

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()

1 Comment

be aware of sql injection here ('2222', 'Maria', '[email protected]')

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.