dnT*_*osh 2 python cx-oracle sql-update
在我的 Python 代码中,当我要求用户向 SELECT 输入字符串时,它可以工作,但是当我尝试使用相同输入的 UPDATE 时,不允许我执行
这是连接成功后我的代码
curs = connection.cursor()
str_input1 = str(input("Input : "))
str_input2 = str(input("Input : "))
statement = "UPDATE table SET variable1 = "+str_input1+" WHERE name = "+str_input2
curs.execute(statement)
connection.commit
Run Code Online (Sandbox Code Playgroud)
理论上,以下代码应该可以工作并更新变量,但是我在 curs.execute(statement) 行得到错误说
cx_Oracle.DatabaseError: ORA-00904: John: invalid identifier
Run Code Online (Sandbox Code Playgroud)
John 是 where 子句的 str_input2
也许它的格式给了我一个错误,但我不太确定。
有人可以指出我的代码有什么问题吗?
错误是因为您没有引用值。你会从SELECT语句中得到完全相同的错误。
这些语句搜索name列与字符串匹配的行John:
SELECT * FROM table WHERE name = "John"
UPDATE table SET variable1 = "Hi" WHERE name = "John"
Run Code Online (Sandbox Code Playgroud)
这些语句搜索name列与列匹配的John行——如果没有John列,那就是一个错误:
SELECT * FROM table WHERE name = John
UPDATE table SET variable1 = "Hi" WHERE name = John
Run Code Online (Sandbox Code Playgroud)
所以,你可以通过在值周围加上引号来解决这个问题。
但你真的,真的,真的不应该。这会让您面临SQL 注入攻击,以及您没有正确引用或转义特殊字符的愚蠢错误,以及数据库引擎无法判断您正在一遍又一遍地运行相同查询的性能问题,等等.
您想要做的是使用SQL parameters,而不是尝试格式化字符串。我不记得哪个参数风格cx_Oracle用途,但你可以import cx_Oracle; print(cx_Oracle.paramstyle),并期待它在表中找出来。然后执行以下操作:
statement = "UPDATE table SET variable1 = :v WHERE name = :n"
curs.execute(statement, {'v': str_input1, 'n': str_input2})
Run Code Online (Sandbox Code Playgroud)
另外,一些旁注:
connection.commit什么都不做;您只是引用该commit方法,而不是调用它。你需要括号:connection.commit()str(input())毫无意义。该input函数总是返回一个字符串,所以没有理由调用str它。(除非你使用Python 2.x中,在这种情况下,你应该使用raw_input(),它返回一个字符串,而不是使用input到eval的字符串开放同种的安全问题,因为SQL注入攻击上面,只把它转换回到字符串。)| 归档时间: |
|
| 查看次数: |
15446 次 |
| 最近记录: |