Python在postgresql表中查找带有单引号的字符串

标签 python python-3.x postgresql psycopg2

我需要从我的 psql 表中查找包含多个单引号的字符串。我当前的解决方案是用这样的双单引号替换单引号:

sql_query = f"""SELECT exists (SELECT 1 FROM {table_name} WHERE my_column = '{my_string.replace("'","''")}' LIMIT 1);"""
cursor = connection.cursor()
cursor.execute(sql_query)

对于这种格式化有更好的解决方案吗?

最佳答案

我通过这样的查询解决了这个问题

sql_query = f"""SELECT exists (SELECT 1 FROM {table_name} WHERE my_column = %s LIMIT 1);"""
cursor = connection.cursor()
cursor.execute(sql_query, (mystring,))

在这种情况下,它以这样的方式格式化mystring,它不会作为sql查询执行,也不会导致问题中提到的问题

关于Python在postgresql表中查找带有单引号的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70621488/

相关文章:

ruby-on-rails - 通过 includes 从 id 数组中选择

python - 如何在 Django 表单中创建字段列表

python - 从句子列表中删除单词列表的简单方法是什么?

Python Find max in dataframe 列以循环查找所有值

python - 装饰器可以装饰递归函数吗?

postgresql - 在 Postgresql 上使用 group by 计数

Perl Mojolicious + PgAsync 插件——泄漏数据库连接?

python - python 中的 tensorflow 夜间轮

python - NodeJS 应用程序无法从 Python shell 获取输入

python-3.x - 复制 vim 中的行以在 ter 命令打开的上述窗口中执行?