gpt4 book ai didi

python - python中的数据库查询语法

转载 作者:行者123 更新时间:2023-12-01 05:36:05 24 4
gpt4 key购买 nike

我有一个从 python 脚本运行的查询。它看起来像这样:

app_phone=str(5555555555)
query_string=""""select biz_name, biz_addr, biz_owner
from business_t
where regexp_replace(biz_phone_1, E'\\\\D|^1', '', 'g') = '"""+app_phone+"""'
or regexp_replace(biz_phone_2, E'\\\\D|^1', '', 'g') = '"""+app_phone+"""'
or regexp_replace(biz_cell_1, E'\\\\D|^1', '', 'g') = '"""+app_phone+"""'
or regexp_replace(biz_cell_2, E'\\\\D|^1', '', 'g') = '"""+app_phone+"""'
;"""
result=run_query(query_string)

查询运行良好 - 我的问题实际上是,以一种易于阅读的格式“按语法”编写此类查询的最佳方法是什么,并且不会向脚本添加不必要的处理?或者这是一种很好的写法吗?

这看起来有点难看,但也许这只是代码中需要原始 SQL 的诅咒。

最佳答案

我可以推荐以下选项:

1)我将直接在查询中嵌入查询参数,然后将其作为元组/字典单独传递给cursor.execute(请参阅您的数据库API以获取确切的格式)方法:

app_phone = 5555555555
query_string="""SELECT biz_name, biz_addr, biz_owner
FROM business_t
WHERE regexp_replace(biz_phone_1, E'\\\\D|^1', '', 'g') = '%(phone)s'
OR regexp_replace(biz_phone_2, E'\\\\D|^1', '', 'g') = '%(phone)s'
OR regexp_replace(biz_cell_1, E'\\\\D|^1', '', 'g') = '%(phone)s'
OR regexp_replace(biz_cell_2, E'\\\\D|^1', '', 'g') = '%(phone)s';
"""
result = run_query(query_string, {'phone': app_phone})

此解决方案将使您免受(大多数)sql 注入(inject)攻击

2) 要构建查询,您可以考虑使用 sql 查询构建库 ( https://pypi.python.org/pypi/python-sql/0.2 )。这将允许您根据表达式构建 SQL 查询,而不是使用字符串编辑。不确定此查询生成器是否支持在 where 中使用正则表达式

3)您可以尝试使用循环,但它是否变得更具可读性的问题将是主观的,恕我直言:

app_phone = 5555555555
cmp_phones = "regexp_replace(%s, E'\\\\D|^1', '', 'g') = '%%(phone)s'"
db_phone_columns = (biz_phone_1, biz_phone_2, biz_cell_1, biz_cell_2)
where_condition = 'OR'.join(cmp_phones % phone for phone in db_phone_columns)
result = run_query(query_string, {'phone': app_phone}
query_string="""SELECT biz_name, biz_addr, biz_owner
FROM business_t
WHERE %(where_condition)s;""" %
{'where_condition': where_condition}
result = run_query(query_string, {'phone': app_phone})

我个人认为解决方案 1) 最具可读性

4)使用以手机为参数的存储过程

5) 示例中演示了我个人更喜欢的查询字符串内的查询格式

关于python - python中的数据库查询语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19035075/

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