Vic*_*ice 5 python oracle cx-oracle
我正在使用cx_Oracle来访问我们的数据库.我希望用户能够输入电台ID,例如:
stationID =(无论用户在提示时输入什么)
cursor.execute('''select cruise, station, stratum
from union_fscs_svsta
where station=stationID
order by cruise''')
Run Code Online (Sandbox Code Playgroud)
因为语句需要是一个字符串,我如何合并一个用户定义的变量?
怎么不这样做:
id = raw_input("Enter the Station ID")
query = "select foo from bar where station={station_id}"
cursor.execute(query.format(station_id=id))
Run Code Online (Sandbox Code Playgroud)
如果有人输入恶意sql字符串,它将被执行.
而不是使用python格式化字符串,让数据库后端为您处理它.具体如何执行此操作取决于您使用的数据库.我认为(?)这对Oracle来说是正确的,但我无法测试它.一些数据库使用不同的字符(例如,?而不是%s在SQLite的情况下).
id = raw_input("Enter the Station ID")
query = "select foo from bar where station=%s"
cursor.execute(query, [id])
Run Code Online (Sandbox Code Playgroud)
编辑:显然,cx_Oracle默认为"命名"参数样式(您可以通过查看来查看cx_Oracle.paramstyle.).在这种情况下,你会做这样的事情:
query = "select foo from bar where station=:station_id"
cursor.execute(query, station_id=id)
Run Code Online (Sandbox Code Playgroud)