基于Python MySQLdb execute table variable和MySQL LOAD DATA LOCAL INFILE example in python?,这应该起作用:
import pymysql, os
directory = os.path.join('path', 'to', 'directory')
filename = 'my_filename.csv'
filepath = os.path.join(directory, filename)
to_table_name = "my_table"
connection = pymysql.connect(..., local_infile=True)
with connection.cursor() as cursor:
load_statement = """
load data local infile %s
into table %s
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\\n'
ignore 1 lines
"""
cursor.execute(load_statement % (filepath, to_table_name, ))
connection.commit()
connection.close
但是我仍然看到此错误:
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 '/path/to/directory/my_filename.csv\n into ' at line 1")
当我在不使用参数的情况下运行此程序时,即写出实际的文件路径和表名,就可以了。
任何帮助将不胜感激。
您还应该使用Execute的内置功能来进行字符串格式化(这样可以避免MYSQL注入攻击和错误)...与其使用%(字符串插值)将参数传递给load_statement,不如将参数作为执行参数传递给
cursor.execute(load_statement , (filepath, to_table_name ))
注意逗号而不是%