我已经看到以下两个答案:
这两种解决方案都不适合我。我运行下面的代码,每次完成都没有任何错误,但根本没有修改mysql表Compounds
,我已经验证输入文件的格式与格式完全匹配我的mysql表并且它被正确分隔而不是空。
import os, sys
import mysql.connector
from mysql.connector import errorcode
from mysql.connector.constants import ClientFlag
TABLE_NAME = "Compounds"
fullDataFile = "data/compounds/parsed/fullData.csv"
cnx = mysql.connector.connect(user='kharland', passwd='password', db='mydb', client_flags=[ClientFlag.LOCAL_FILES])
cursor = cnx.cursor()
print "loading data file: %s/%s" % (os.getcwd(), fullDataFile)
try:
cursor.execute = (
"LOAD DATA LOCAL INFILE '%s/%s'"
" REPLACE"
" INTO TABLE `%s`"
" FIELDS TERMINATED BY '^'"
" LINES TERMINATED BY '\n'"
" (PUBCHEM_COMPOUND_CID,"
" PUBCHEM_COMPOUND_CANONICALIZED,"
" PUBCHEM_CACTVS_COMPLEXITY,"
" PUBCHEM_CACTVS_HBOND_ACCEPTOR,"
" PUBCHEM_CACTVS_HBOND_DONOR,"
" PUBCHEM_CACTVS_ROTATABLE_BOND,"
" PUBCHEM_CACTVS_SUBSKEYS,"
" PUBCHEM_IUPAC_INCHI,"
" PUBCHEM_IUPAC_INCHIKEY,"
" PUBCHEM_EXACT_MASS,"
" PUBCHEM_MOLECULAR_FORMULA,"
" PUBCHEM_MOLECULAR_WEIGHT,"
" PUBCHEM_OPENEYE_CAN_SMILES,"
" PUBCHEM_OPENEYE_ISO_SMILES,"
" PUBCHEM_CACTVS_TPSA,"
" PUBCHEM_MONOISOTOPIC_WEIGHT,"
" PUBCHEM_TOTAL_CHARGE,"
" PUBCHEM_HEAVY_ATOM_COUNT,"
" PUBCHEM_ATOM_DEF_STEREO_COUNT,"
" PUBCHEM_ATOM_UDEF_STEREO_COUNT,"
" PUBCHEM_BOND_DEF_STEREO_COUNT,"
" PUBCHEM_BOND_UDEF_STEREO_COUNT,"
" PUBCHEM_ISOTOPIC_ATOM_COUNT,"
" PUBCHEM_COMPONENT_COUNT,"
" PUBCHEM_CACTVS_TAUTO_COUNT);" %
(os.getcwd(), fullDataFile, TABLE_NAME))
cnx.commit()
except mysql.connector.Error as e:
sys.stderr.write("x Failed loading data: {}\n".format(e))
但是,如果我将此查询打印到终端然后在mysql中运行,那么它的工作正常。有没有理由mysql lib可能无法运行实际查询,或者我错过了一些函数调用?
答案 0 :(得分:1)
MySQL不接受标识符的绑定占位符。在这种情况下,表的名称。这必须是SQL文本的一部分。您只能使用绑定占位符提供值。
你可以这样做:
SELECT t.id FROM mytable t WHERE t.foo = :val
^^^^
但这无效:
SELECT t.id FROM :mytable t WHERE t.foo = 'bar'
^^^^^^^^
您可以执行sprintf
类型操作作为前一步骤,以生成包含实际表名的SQL文本(字符串),然后将该SQL文本(字符串)提交给MySQL。
当你到达那个cursor.execute
时,你需要SQL文本包含表名作为字符串的一部分。 (也可能是文件的名称必须指定为文字,并且不能是占位符,但我不确定。我确定的是表名。)
作为测试,尝试硬编码表名“Compounds”并将文件名硬编码到SQL文本中......
cursor.execute = (
"LOAD DATA LOCAL INFILE '/opt/data/compounds/parsed/fullData.csv'"
" REPLACE"
" INTO TABLE `Compounds`"