mysql/connector python 查询适用于 mysql 但不适用于 python

mysql/connector python query works in mysql but not python

我看到了以下两个答案:

这两种解决方案都不适合我。我正在 运行ning 下面的代码,它每次都没有任何错误地完成,但根本没有修改 mysql table Compounds,并且我已经验证了输入文件的格式与我的 mysql table 的格式完全匹配,并且分隔正确且不为空。

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 是否有可能无法 运行 实际查询,或者我错过了一些函数调用?

MySQL 不接受标识符的绑定占位符。在本例中,名称为 table。那必须是 SQL 文本的一部分。您只能使用绑定占位符提供

你可以这样做:

SELECT t.id FROM mytable t WHERE t.foo = :val
                                         ^^^^

但这无效:

SELECT t.id FROM :mytable t WHERE t.foo = 'bar'
                 ^^^^^^^^ 

您可以先执行 sprintf 类型的操作,生成包含实际 table 名称的 SQL 文本(字符串),然后提交SQL 文本(字符串)到 MySQL.

当您到达 cursor.execute 时,您需要 SQL 文本以 包含 table 名称作为字符串的一部分。 (也有可能文件名必须指定为文字,不能是占位符,但我不确定。我确定的是 table 名称。)


作为测试,尝试将 table 名称硬编码 "Compounds" 并将文件名硬编码到 SQL 文本中...

cursor.execute = (
    "LOAD DATA LOCAL INFILE '/opt/data/compounds/parsed/fullData.csv'"
    " REPLACE"
    " INTO TABLE `Compounds`"