You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修正Python执行MySQL查询时的语法错误?

Fixing MySQL Syntax Error in Python Query

Got it, let's sort out this SQL syntax error you're hitting. The root cause is super straightforward: **MySQL requires identifiers (like column names) with spaces or special characters to be wrapped in backticks ()**. Your query has column names like Master Job NameandSource File Name Lnd` that include spaces, but you didn't wrap them in backticks—so MySQL gets confused mid-parsing, thinking "Name" is a new keyword instead of part of the column name.

Here's the corrected Python code with the proper SQL formatting:

with db.cursor() as cur:
    # Wrap space-containing column names in backticks, use triple quotes for clean formatting
    query_meta = """
    SELECT TRIM(CONCAT_WS('|', `Master Job Name`, `Seq`, `TableName`, `Source File Name Lnd`, `landingdfname`, `TargetPath`, `query1`, `Execution Sequence`)) 
    FROM DUAL
    """
    cur.execute(query_meta)
    res = cur.fetchall()

Key fixes made:

  • Every column name with spaces (e.g., Master Job Name, Execution Sequence) is wrapped in backticks to tell MySQL it's a single, complete identifier.
  • Used triple double-quotes (""") to define the SQL string—this makes the query easier to read and avoids having to escape single quotes inside the string.
  • Uppercased SQL keywords (SELECT, TRIM, FROM) as a best practice for readability (this doesn't affect functionality, but makes the query easier to scan).

This should resolve the ProgrammingError you're seeing, since MySQL will now correctly parse all your column names.

内容的提问来源于stack exchange,提问作者jay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:04:35