gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:49:46 29 4
gpt4 key购买 nike

我需要从我的 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com