以下代码在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)
错误: 文件“”,第7行 insert_query = INSERT INTO film_text(film_id,title,description)值(“ 1001”,“ ZZZ ZORRO”,“ Zorro必须与柏林的女化者作战”); ^ SyntaxError:语法无效
答案 0 :(得分:2)
insert_query的类型将是一个字符串。
insert_query = "INSERT INTO film_text (film_id, title, description) VALUES ('1001','ZZZ ZORRO','Zorro must Fight a Womanizer in Berlin')"
答案 1 :(得分:1)
您也可以像这样直接编写代码
cursor.execute("""INSERT INTO film_text (film_id, title, description) VALUES ('1001','ZZZ ZORRO','Zorro must Fight a Womanizer in Berlin'""");
答案 2 :(得分:1)
您忘记将查询用引号引起来。下面的代码应该可以正常工作:
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)
答案 3 :(得分:0)
您应该在查询字符串中加上引号
insert_query= "INSERT INTO film_text (film_id, title, description)
VALUES ('1001','ZZZ ZORRO','Zorro must Fight a Womanizer in Berlin')";
答案 4 :(得分:0)
如果不打算对来自 python 的数据做一些非常高级的事情,也许最好使用 jupyter kernel 来使用纯 SQL 中的数据库。