使用python处理查询字符串中的撇号 [英] Handle apostrophe in query string using python
问题描述
我正在尝试使用Python查询Redshift.我正在生成一个查询字符串,如下所示:我正在使用 psycopg2
作为建立连接的库.
I am trying to query Redshift using Python.
I am generating a query string which looks like the one below:
I am using psycopg2
as the library to establish the connection.
Select lat, lon, gender from table_x where x_name = "namestring"
如果我的姓名字符串包含'
,则查询字符串将无法执行.
If my name string contains an '
, the query string fails to execute.
有人可以告诉我避免这种错误的方法吗?我有大约25k个名称的列表,因此不能使用 \'
对其进行转义.
Can someone tell me a way to avoid this error? I have a list of approximately 25k names and hence escaping each of them with a \'
is not an option.
推荐答案
使用参数化查询,如
这避免了由于使用参数化查询构造而不是字符串连接而导致自引用的问题. This avoids the problem of self-quoting dur to using parametrized query construction instead of string concattenation. 请参见小鲍比表/对妈妈的利用和Google sql注入,以及其他原因,请不要使用字符串-并存. See Little Bobby Tables / Exploit of a Mom and google sql injection fo rother reasons not to string-concattenate. 这篇关于使用python处理查询字符串中的撇号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!