Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I can recommend the following options:</p> <p>1) I would embed query parameters directly in the query, I would pass then separately as a tuple/dict to the cursor.execute (see your db api for exact formatting) method: </p> <pre><code>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}) </code></pre> <p>This solution will save you from (most) sql injection attacks</p> <p>2) To build the query you can consider using sql query building library (<a href="https://pypi.python.org/pypi/python-sql/0.2" rel="nofollow">https://pypi.python.org/pypi/python-sql/0.2</a>). That will allow you to build SQL queries in terms of expressions, not using string editing. Not sure if this query builder will support usage of regexp in where though</p> <p>3) You can try to use loop, but the question if it's become more readable will be subjective, imho:</p> <pre><code>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}) </code></pre> <p>I personally find solution 1) most readable</p> <p>4) Use stored procedure with phone as a parameter</p> <p>5) Formatting of the query inside the query string that I personally prefer is demonstrated in the examples</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload