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

从Tkinter/Python脚本向Oracle数据库插入记录报错求助

问题解决:Python+Oracle插入记录的语法错误修正

你的两段代码都因不符合Oracle INSERT语句的语法规范报错,以下是问题分析和修正方案:

错误原因分析

  1. ORA-00917: missing comma
    你写的VALUES (username = '%s')是错误语法:VALUES子句仅接收取值列表,不能用「列名=值」的格式;且仅插入单个值时,必须明确指定目标列名,否则Oracle无法确定值对应的列。

  2. ORA-00933: SQL command not properly ended
    VALUES username = '%s'完全违反SQL语法,VALUES后必须用括号包裹取值列表。

正确代码实现

重点:禁止用字符串拼接传递参数(易出语法错误、存在SQL注入风险),使用oracledb的参数绑定功能:

def add_record():
    username = grp_entry.get()

    oracledb.init_oracle_client(config_dir='/Desktop')

    conn = oracledb.connect(
        user="<username>",
        password="<password>",
        dsn="dsn")        
    c = conn.cursor()

    # 指定目标列,用参数占位符绑定值(推荐写法)
    add_sql = "INSERT INTO ut_om_reports (username) VALUES (:1)"
    c.execute(add_sql, [username])

    conn.commit()
    # 确保连接关闭,也可使用with语句自动管理连接
    try:
        conn.close()
    except Exception:
        pass

补充说明

如果需要插入多列,只需扩展SQL语句和参数列表即可:

# 示例:插入id、username、create_time三列
add_sql = "INSERT INTO ut_om_reports (id, username, create_time) VALUES (:1, :2, :3)"
c.execute(add_sql, [1001, username, "2024-05-20"])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:30:06