2016-01-13 74 views
1

我想根据用户输入的内容查询Oracle表中特定ID的记录。基于用户输入显示来自Oracle查询的结果

这里是我的代码:

import cx_Oracle 
con = cx_Oracle.connect('dbuser/[email protected]_host/service_ID') 
cur = con.cursor() 
id_number = raw_input('What is the ID Number?') 
cur.execute('select id, info from oracle_table_name where id=:id_number') 
for result in cur: 
    print "test", result 
cur.close() 
con.close() 

以下错误弹出:cx_Oracle.DatabaseError: ORA-01008: not all variables bound

当我删除用户输入和变量替换和运行查询,一切工作正常。

回答

1

:id_number你的SQL是一个参数(变量)。你需要提供它的价值。 execute方法接受参数作为第二个参数。

例子: query = "select * from some_table where col=:my_param" cursor.execute(query, {'my_param': 5})

检查在http://cx-oracle.readthedocs.org/en/latest/cursor.html#Cursor.execute

+0

对于my_param的设置值,这很有效。问题的另一部分是关于采取动态用户输入并将其用作my_param值以实现相同的结果。 – Tiberius

+0

这里用你的动态值,即'{'my_param':id_number}'替换示例中的“5”(在参数字典中)。 –

1

的文档给我分配一个名称user_value:

user_value = raw_input('What is the ID Number?') 

然后在执行语句中引用它:

cur.execute(query, {'id': (user_value)}) 

感谢Radoslaw-Roszkowiak的协助!