【问题标题】:mysql.connector.errors.ProgrammingError: 1064 (42000) & XML parsingmysql.connector.errors.ProgrammingError: 1064 (42000) & XML 解析
【发布时间】:2016-12-20 17:57:20
【问题描述】:

我正在尝试在 MYSQL 中使用 XML 字符串填充列。当我运行我的 python 脚本时,我收到以下错误。我使用文件名作为 id,我相信我以某种方式错误地解析了 XML。

mysql.connector.errors.ProgrammingError: 1064 (42000): 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 ' 附近使用的正确语法

cursor = cnx.cursor(buffered=True)

tree = ET

for a in os.listdir(mydir):
    if a.endswith(".xml"):
        print os.path.basename(a)
        j=ET.parse(mydir+"/"+a)
        a = ''.join(a.split())
        a = a[:-9]
        root = j.getroot()
        xmlstr = ET.tostring(root, encoding='utf8')
        xmlstr
        print a
        query = """UPDATE %s.%s SET col1= (%s) WHERE col2 = (%s)""" % (mysql_db,mysql_table,xmlstr,a)
        cursor.execute(query)

你知道发生了什么错误吗?

当我在执行之前打印查询时,我得到以下信息

UPDATE triageprediction.triagepredictionsamples SET CtXml= (<?xml version='1.0' encoding='utf8'?>
<CAS version="2">
    <uima.cas.Sofa _id="3" _indexed="0" mimeType="text" sofaID="_InitialView" sofaNum="1" sofaString="The Enmore Practice
&#10;
more xml.....
    </uima.cas.FSArray>
</CAS>) WHERE REFERRALID = (1187116)
Traceback (most recent call last):
  File "C:\XML_Formatter_v2\loadxml.py", line 47, in <module>
    cursor.execute(query)
  File "C:\Python27\lib\site-packages\mysql\connector\cursor.py", line 551, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 490, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "C:\Python27\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2">
    <uima.cas.Sofa _id="3" _indexed="0" mimeType="text" sofaID="_InitialView' at line 1

【问题讨论】:

  • 在执行前打印出query。你看到打印了什么?
  • 嗨@alecxe,我已经更新了帖子以包含它,即使我添加 ("%s") 它也会失败。我知道我在做一些非常愚蠢的事情,只是不确定是什么。

标签: python mysql xml


【解决方案1】:

看来您的问题在于您将参数放入查询的方式。目前,您使用的字符串格式不仅危险(请参阅SQL injections),而且是正确放置引号、转义和数据类型转换问题的根源。

您应该使用参数化查询

query = """
    UPDATE 
        {db}.{table} 
    SET 
        col1 = %s 
    WHERE 
        col2 = %s""".format(db=mysql_db, table=mysql_table)
cursor.execute(query, (xmlstr, a))

注意xmlstra 如何分别传递给execute()。另请注意,我们没有在 %s 占位符周围放置任何内容 - MySQL 数据库驱动程序将自动处理引用和转义。

但是,我们不能参数化数据库、表和列名,为此,我们将使用字符串格式。不过,请确保正确清理 mysql_dbmysql_table 变量值。

【讨论】:

  • 嘿@alecxe 参数化表名仍然不受支持?
  • @NI6 是的,据我所知,它不是而且很可能永远不会:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
相关资源
最近更新 更多