【问题标题】:User input variables in cx_Oracle?cx_Oracle 中的用户输入变量?
【发布时间】:2012-11-18 23:50:31
【问题描述】:

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

stationID=(用户在提示时输入的内容)

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

由于语句需要是字符串,如何合并用户定义的变量?

【问题讨论】:

  • 您是在问如何安全地做到这一点,或者只是如何做到这一点? (永远不要相信用户输入...... SQL注入等)
  • 这是真的,回复:输入...有没有更安全(更安全)的方式来做到这一点?

标签: python oracle cx-oracle


【解决方案1】:

怎么做:

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)

【讨论】:

  • 这对我不起作用 - 我必须将参数作为字典提交 - cursor.execute(query, {'station_id':id})。否则,请注意,谢谢!
  • 您可以在 cx_Oracle 中使用位置参数如“:0”、“:1”等。
  • 你能举个例子@Beli select * from :0.:1 if 0 is schemaname and 1 is tablename
猜你喜欢
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 2018-11-26
相关资源
最近更新 更多