用户输入变量在cx_Oracle中?

时间:2012-11-30 18:01:22

标签: python oracle cx-oracle

我正在使用cx_Oracle来访问我们的数据库。我希望用户能够输入电台ID,例如:

stationID =(无论用户在提示时输入什么)

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

因为语句需要是一个字符串,如何合并用户定义的变量?

1 个答案:

答案 0 :(得分:8)

如何

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

如果有人输入恶意sql字符串,它将被执行。

不要使用python格式化字符串,而是让数据库后端为您处理。具体如何执行此操作取决于您使用的数据库。我认为(?)这对Oracle来说是正确的,但我无法测试它。某些数据库使用不同的字符(例如,在SQLite的情况下,?而不是%s

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

修改:显然,cx_Oracle默认为“已命名”的参数样式(您可以通过查看cx_Oracle.paramstyle来查看此内容)。在这种情况下,你会做这样的事情:

query = "select foo from bar where station=:station_id"
cursor.execute(query, station_id=id)
相关问题