cx_Oracle中的用户输入变量?

2024-06-01 01:40:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

因为语句必须是字符串,所以如何合并用户定义的变量?


Tags: 用户fromid数据库execute站点selectcursor
1条回答
网友
1楼 · 发布于 2024-06-01 01:40:47

如何做到这一点:

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来格式化字符串,而是让数据库后端为您处理它。具体怎么做取决于您使用的数据库。我想(?)这对甲骨文来说是正确的,但我不能测试它。有些数据库使用不同的字符(例如?,而不是%s(对于SQLite)。

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

编辑:显然,cx_Oracle默认为“命名”paramstyle(您可以通过查看cx_Oracle.paramstyle来检查这一点)。在这种情况下,你应该这样做:

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

相关问题 更多 >