SQL 查询在插入 table 时出现问题

SQL query is causing problem while inserting into table

我尝试使用 pymysql 库插入数据框。 它给出了这个错误:

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''bestwebsites' ('Rank','Score','Category','Audience','URL','Links','Desc') VALUE' at line 1")

import pandas as pd 
import re
# import sqlalchemy
import pymysql


df = pd.read_csv('final_data.csv')
df = df.drop(['blank','Unnamed: 0'], axis=1)
df['Desc']
df['Desc'] = df['Desc'].str.replace("[-',’]",'').astype(str)
df.columns

connection = pymysql.connect(host='localhost',
                             user='root',
                             password='root',
                             db='pythondb')

cursor = connection.cursor()

cols = "','".join([str(i) for i in df.columns.tolist()])

for i,row in df.iterrows():
    sql = "INSERT INTO 'bestwebsites' ('" +cols+ "') VALUES (" + "%s,"*(len(row)-1) + "%s)"
    cursor.execute(sql,list(row))

    connection.commit()
connection.close()    

我尝试使用 sqlalchemy 它正在工作

engine = sqlalchemy.create_engine('mysql+pymysql://root:root@localhost:3306/pythondb')

df.to_sql(name='bestwebsites',
        con=engine,
        index=False,
        if_exists='replace') 

列名称(和 table 名称)不应用单引号引起来。如果它们符合不带引号的标识符的 MySQL 规则,您可以使用 unquote 它们,或者使用反引号进行引用:

cols = "`,`".join([str(i) for i in df.columns.tolist()])

for i,row in df.iterrows():
    sql = "INSERT INTO `bestwebsites` (`" +cols+ "`) VALUES (" + "%s,"*(len(row)-1) + "%s)"
    cursor.execute(sql,list(row))   

connection.commit()
connection.close()

旁注:先执行所有 insert,然后再提交比每次插入后都提交效率更高。