0

您好,我想使用“加载数据 Infile”将数据从 excel 文件或 .txt 导入数据库,但我的文件的路径包含“\”,Mysql 不接受女巫

要清楚这是我的 Python 代码:

def parcourir(self):
        fi=QFileDialog.getOpenFileName(self)
        self.Pathfile.setText(fi)

def chargeFile(self):        
        try:
            fiche=open(self.Pathfile.text(),'r')
        except IOError :
            QtGui.QMessageBox.warning(self,"erreur","fichier nontrouvé")
        connection = MySQLdb.connect (host = "localhost", user = "root", passwd = "", db = "lexique")
        cursor = connection.cursor()
        query="LOAD DATA INFILE 'self.Pathfile.text()' INTO TABLE tbl_lexique FIELDS TERMINATED BY ',' ENCLOSED BY '\"'LINES TERMINATED BY '\n'"
        cursor.execute( query )
        connection.commit()
        ...................
4

2 回答 2

1

您可能应该考虑使用参数化查询:

query="""
    LOAD DATA INFILE '%s' INTO TABLE tbl_lexique 
    FIELDS TERMINATED BY '%s' 
    ENCLOSED BY '%s' 
    LINES TERMINATED BY '%s'
    """

# you can also try converting your windows
# path to a posix path
path = self.Pathfile.text().replace('\\', '/')
cursor.execute(query, (path, ',', '"', '\n'))
于 2012-06-20T01:11:40.050 回答
0

好吧,它现在终于可以工作了:)我只是提出了这个查询:

query = "LOAD DATA INFILE '%s' " % self.Pathfile.text()
query += " INTO TABLE tbl_lexique FIELDS TERMINATED BY ',' ENCLOSED BY '\\\"' LINES TERMINATED BY '\\n'" 
cursor.execute( query )
于 2012-06-20T22:55:24.033 回答