我知道该主题的变体已在别处讨论过,但其他主题都没有帮助.
I know that variants of this topic have been discussed elsewhere, but none of the other threads were helpful.
我想把一个字符串从python交给sql.然而,字符串中可能会出现撇号 (').我想用反斜杠转义它们.
I want to hand over a string from python to sql. It might however happen that apostrophes (') occur in the string. I want to escape them with a backslash.
sql = "update tf_data set authors=\'"+(', '.join(authors).replace("\'","\\\'"))+"\' where tf_data_id="+str(tf_data_id)+";"但是,这将始终在我的字符串中给出 \\' .因此,反斜杠本身被转义,sql语句不起作用.
However, this will always give \\' in my string. Therefore, the backslash itself is escaped and the sql statement doesn't work.
有人可以帮助我或为我提供替代方法吗?谢谢
Can someone help me or give me an alternative to the way I am doing this? Thanks
推荐答案完全不要.也不要连接 sql 查询,因为它们容易被 sql 注入.
Simply don't. Also don't concatenate sql queries as these are prone to sql injections.
相反,使用参数化查询:
Instead, use a parameterized query:
sql = "update tf_data set authors=%(authors)s where tf_data_id=%(data_id)s" # or :authors and :data_id, I get confused with all those sql dialects out there authors = ', '.join(authors) data_id = str(tf_data_id) # db or whatever your db instance is called db.execute(sql, {'authors': authors, 'data_id': data_id})更多推荐
用python中字符串中的单个反斜杠替换双反斜杠
发布评论