2016-01-13 63 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的協助!