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?
How not to do it:
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%sin the case of SQLite).Edit: Apparently,
cx_Oracledefaults to a “named” paramstyle (You can check this by having a look atcx_Oracle.paramstyle.). In that case, you’d do something like this: