用python中字符串中的单个反斜杠替换双反斜杠

编程入门 行业动态 更新时间:2024-10-24 13:25:44
本文介绍了用python中字符串中的单个反斜杠替换双反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道该主题的变体已在别处讨论过,但其他主题都没有帮助.

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中字符串中的单个反斜杠替换双反斜杠

本文发布于:2023-11-06 14:33:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563954.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斜杠   字符串   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!