Django Command: Load Data Mysql



写一个django命令,从一个目录导入txt文件到数据库。数据库被创建,但是当运行时,我得到可爱的,难以描述的错误django.db.utils.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' at line 1")。我不知道该调查什么。当我尝试将单个文件放入mysql门户时,它似乎可以工作。我如何跳转到Django命令?

下面是命令代码:

def handle(self, *args, **options):
self.stdout.write("nStarting...")
with connections['wk'].cursor() as cursor:
db_name = settings.DATABASES['wk']['NAME']
for path in glob.glob(f'{options["p"]}/*[!.sql]'):
table_name = f'{db_name}.{path.rsplit("/")[-1].lower()}'
cursor.execute("LOAD DATA INFILE '%s' INTO TABLE %s", [path, table_name])

您应该只让连接器替换数据值,而不替换文件名、表名和字段名。这里发生的是你得到了双引号。

:

cursor.execute("LOAD DATA INFILE '%s' INTO TABLE %s" % (path, table_name))

cursor.execute(f"LOAD DATA INFILE '{path}' INTO TABLE {table_name}")

最新更新