简体   繁体   English

Python mysql 参数和加载数据命令(还是不行)

[英]Python mysql parameters and load data command (still not working)

Based on Python MySQLdb execute table variable and MySQL LOAD DATA LOCAL INFILE example in python?基于Python MySQLdb 执行表变量Python 中的MySQL LOAD DATA LOCAL INFILE 示例? this should work:这应该有效:

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

But I'm still seeing this error:但我仍然看到这个错误:

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

When I run this without the parameters ie writing the actual filepath and table name it works.当我在没有参数的情况下运行它时,即写入实际的文件路径和表名,它可以工作。

Any help would be much appreciated.任何帮助将非常感激。

You should use the built in ability of Execute to do your string formatting also (this avoids MYSQL Injection attacks and errors) ... Rather than passing the parameters to the load_statement using % (String Interpolation) , pass that as parameters to execute您还应该使用 Execute 的内置功能来进行字符串格式化(这可以避免 MYSQL 注入攻击和错误)......而不是使用 % (String Interpolation) 将参数传递给 load_statement ,而是将其作为参数传递给执行

 cursor.execute(load_statement , (filepath, to_table_name ))

Notice the comma instead of a %注意逗号而不是 %

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM