Max*_*axS 0 python str-replace pymysql
我知道这个主题的变体已经在别处讨论过,但其他线程都没有帮助.
我想将一个字符串从python移交给sql.然而,可能会发生撇号(')出现在字符串中.我想用反斜杠逃脱它们.
sql = "update tf_data set authors=\'"+(', '.join(authors).replace("\'","\\\'"))+"\' where tf_data_id="+str(tf_data_id)+";"
Run Code Online (Sandbox Code Playgroud)
但是,这总是会\\'在我的字符串中给出.因此,反斜杠本身被转义,并且sql语句不起作用.
有人可以帮助我,或者让我替代我这样做的方式吗?谢谢
根本就不要.
也不要连接sql查询,因为它们容易进行sql注入.
而是使用参数化查询:
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})
Run Code Online (Sandbox Code Playgroud)