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

Oracle ORA-01036错误求助:插入土壤数据时变量名/编号非法

解决Oracle ORA-01036: illegal variable name/number错误

嘿,我来帮你搞定这个烦人的Oracle错误!

错误原因分析

你这里踩了个常见的数据库驱动语法坑——cx_Oracle和MySQL等数据库的占位符规则不一样。你用了MySQL风格的%s作为变量占位符,但Oracle数据库只认冒号开头的绑定变量(比如:1、:2这种位置编号,或者:name这种命名变量)。当你把%s传给Oracle时,它完全识别不了这些“变量”,自然就抛出了"illegal variable name/number"的错误。

解决方案

只需要把SQL语句里的%s替换成Oracle支持的占位符格式就行,有两种常用写法:

方式1:位置编号占位符

用:1、:2……对应元组里的参数顺序,修改后的代码片段如下:

try:
    con = cx_Oracle.connect('hr/hr@192.168.56.1/xepdb1')
    cursor = con.cursor()
    # 把%s替换成:1到:5,对应元组里的每个参数
    cursor.execute('INSERT INTO soildata (soil_name, soil_text, soil_colour, soil_waterhold, soil_chemicalequ) ' 
                   'VALUES(:1, :2, :3, :4, :5)', (name, texture, colour, capacity, equation))
    con.commit()
except cx_Oracle.DatabaseError as e:
    print("There is a problem with Oracle", e)
finally:
    if cursor:
        cursor.close()
    if con:
        con.close()

方式2:命名占位符

用有意义的名称作为占位符(比如:name),然后用字典传递参数,可读性更强:

try:
    con = cx_Oracle.connect('hr/hr@192.168.56.1/xepdb1')
    cursor = con.cursor()
    # 用命名占位符,对应字典里的key
    cursor.execute('INSERT INTO soildata (soil_name, soil_text, soil_colour, soil_waterhold, soil_chemicalequ) ' 
                   'VALUES(:name, :texture, :colour, :capacity, :equation)', 
                   {'name': name, 'texture': texture, 'colour': colour, 'capacity': capacity, 'equation': equation})
    con.commit()
except cx_Oracle.DatabaseError as e:
    print("There is a problem with Oracle", e)
finally:
    if cursor:
        cursor.close()
    if con:
        con.close()

两种写法都能解决你的问题,选哪种全看你觉得哪种更符合自己的编码习惯~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:47:39