gpt4 book ai didi

Python mysql 连接器加载语句在错误的目录 Windows 中搜索

转载 作者:行者123 更新时间:2023-11-29 07:25:45 25 4
gpt4 key购买 nike

使用代码:

import mysql.connector
cnx = mysql.connector.connect(user='usr', password='pswd',
host='127.0.0.1',
database='db')

cursor = cnx.cursor()

cursor.execute(
"LOAD DATA INFILE 'C:\\Users\\user\\Documents\\csvFiles\\Lamborghini-data.csv' "
"INTO TABLE lamborghini "
"FIELDS TERMINATED BY ',' "
"ENCLOSED BY '\"' "
"LINES TERMINATED BY '\\n' "
"IGNORE 1 ROWS "
"(model_year, make, model, model_info, price, status, auction_location, auction_year);"
)

我成功连接到数据库,但出于某种原因,加载语句查找“C:\xampp\mysql\data...”中的文件,而不是指定的路径。

这是错误:

Traceback (most recent call last):
File "createAndLoadDB.py", line 42, in <module>
"LOAD DATA INFILE 'C:\\Users\\david\\Documents\\MecumProject2\\MecumScraper\\csvFiles\\Lamborghini-data.csv' "
File "C:\Users\david\Anaconda3\envs\MecumDBEnv\lib\site-packages\mysql\connector\cursor.py", line 566, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Users\david\Anaconda3\envs\MecumDBEnv\lib\site-packages\mysql\connector\connection.py", line 549, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Users\david\Anaconda3\envs\MecumDBEnv\lib\site-packages\mysql\connector\connection.py", line 438, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.DatabaseError: 29 (HY000): File 'C:\xampp\mysql\data\UsersdavidDocumentsMecumProject2MecumScrapercsvFilesLamborghini-data.csv' not found (Errcode: 2 "No such file or directory")

它似乎是从我指定的文件中删除'\\',并在'C\xampp\mysql\data...'中搜索它。

如果语句在 .sql 文件中,我可以成功执行该语句,但是在我的 python 脚本中使用它时 mysql.connector 会抛出上述错误。

最佳答案

Why your file path would start with C:\xampp\mysql\data\?

此问题与您的 secure_file_priv 有关。比如我的my.ini

[mysqld]
secure_file_priv = "D:\MySQL\datas"

所以我只能加载D:\MySQL\datas下的csv。但您可以设置 secure_file_priv = "" 来禁用此选项。

How to stop removing the '\' from the file I specify?

在你的字符串前添加r,你需要继续使用\\。为什么会这样,可能是多次传递,字符串从Python传递到mysql。

r"""LOAD DATA INFILE 'C:\\abc\\def.csv'
INTO TABLE test
FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(col);"""

关于Python mysql 连接器加载语句在错误的目录 Windows 中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53905272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com