0

The following code was run in the Jupyter Notebook.

import pandas
import pymysql

connection = pymysql.connect(host='localhost', user='root', password='123456', database='sakila')

cursor=connection.cursor()

insert_query= INSERT INTO film_text (film_id, title, description) VALUES ('1001','ZZZ ZORRO','Zorro must Fight a Womanizer in Berlin');

cursor.execute(insert_query)

connection.commit()

ERROR: File "", line 7 insert_query=INSERT INTO film_text (film_id,title,description) VALUES ('1001','ZZZ ZORRO','Zorro must Fight a Womanizer in Berlin'); ^ SyntaxError: invalid syntax

3
  • Please provide the full error message with your code. It will help others find the bug easily. Jan 19, 2019 at 5:26
  • Looks like you have the table name surrounded by single quotes. Table and field names can have backticks but not quotes, single or double.
    – CharlesEF
    Jan 19, 2019 at 6:06
  • I removed the single quotes, and reran, but received another "Invalid Syntax" error.
    – JavaMon
    Jan 19, 2019 at 6:55

5 Answers 5

1

You can also directly write your code like this

cursor.execute("""INSERT INTO film_text (film_id, title, description) VALUES ('1001','ZZZ ZORRO','Zorro must Fight a Womanizer in Berlin'""");
1

You forgot to wrap the query in quotes. The following code should work perfectly:

import pandas
import pymysql

connection = pymysql.connect(host='localhost', user='root', password='123456', database='sakila')

cursor=connection.cursor()

insert_query= "INSERT INTO film_text (film_id, title, description) VALUES ('1001','ZZZ ZORRO','Zorro must Fight a Womanizer in Berlin');"

cursor.execute(insert_query)
1

The type of insert_query will be a string.

insert_query = "INSERT INTO film_text (film_id, title, description) VALUES ('1001','ZZZ ZORRO','Zorro must Fight a Womanizer in Berlin')"
1
  • Putting double quotes around the insert_query, to make it a string, solved the problem.
    – JavaMon
    Jan 19, 2019 at 15:23
0

you should warp the query string in quote

insert_query= "INSERT INTO film_text (film_id, title, description) 
      VALUES ('1001','ZZZ ZORRO','Zorro must Fight a Womanizer in Berlin')";
0

If don't plan to do highly advanced stuff with the data from python, maybe it's better to use a jupyter kernel to play with the database in plain SQL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.