数据加载infile_python和Qfiledialog

时间:2012-06-20 00:17:46

标签: python excel load qfiledialog

你好我想用excel文件或.txt将数据导入到数据库中,并使用"加载数据Infile"但我文件的路径包含" \"女神不被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()
        ...................

2 个答案:

答案 0 :(得分: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'))

答案 1 :(得分: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 )