MySQL INSERT INTO using Jupyter Notebook ERROR: Invalid syntax

1k views Asked by At

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

5

There are 5 answers

0
robert On

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.

1
Rajan saha Raju On

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')"
0
AudioBubble On

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'""");
0
Tanmoy Krishna Das On

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)
0
ScaisEdge On

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')";