Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User input variables in cx_Oracle?

I'm using cx_Oracle to access our database. I would like the user to be able to input the station ID, for example:

stationID=(whatever the user inputs upon prompting)

cursor.execute('''select cruise, station, stratum
          from union_fscs_svsta
          where station=stationID
          order by cruise''')

Because the statement needs to be a string, how do I incorporate a user-defined variable?

like image 702
Victoria Price Avatar asked Nov 30 '12 18:11

Victoria Price


People also ask

How do you take user input in SQL query?

To do this: Create a select query, and then open the query in Design view. In the Criteria row of the field you want to add a parameter to, type Like "*"&[, the text that you want to use as a prompt, and then ]&"*".

How can we take input from user in DBMS?

The ACCEPT Command. The ACCEPT command is used to obtain input from the user. With it, you specify a user variable and text for a prompt. The ACCEPT command displays the prompt for the user, waits for the user to respond, and assigns the user's response to the variable.

How do you pass values at runtime in PL SQL?

But if you are trying to execute this block of code directly in APEX, then Sodved is correct that you will need to look for first labeling your variable as :num and :num1 respectively and then the calling module must bind the variable to it before you can execute it. hope this helps.

How do you bind variables in PL SQL?

Use a bind variable in PL/SQL to access the variable from SQL*Plus. Bind variables are variables you create in SQL*Plus and then reference in PL/SQL. If you create a bind variable in SQL*Plus, you can use the variable as you would a declared variable in your PL/SQL subprogram and then access the variable from SQL*Plus.


1 Answers

How not to do it:

id = raw_input("Enter the Station ID")
query = "select foo from bar where station={station_id}"
cursor.execute(query.format(station_id=id))

If someone enters a malicious sql string, it will be executed.

Instead of using python to format the string, let the database backend handle it for you. Exactly how you do this depends on the database you're using. I think (?) this is correct for Oracle, but I can't test it. Some databases use different characters (e.g. ? instead of %s in the case of SQLite).

id = raw_input("Enter the Station ID")
query = "select foo from bar where station=%s"
cursor.execute(query, [id])

Edit: Apparently, cx_Oracle defaults to a "named" paramstyle (You can check this by having a look at cx_Oracle.paramstyle.). In that case, you'd do something like this:

query = "select foo from bar where station=:station_id"
cursor.execute(query, station_id=id)
like image 199
Joe Kington Avatar answered Oct 11 '22 13:10

Joe Kington