{"id":308,"date":"2022-03-23T19:12:45","date_gmt":"2022-03-23T19:12:45","guid":{"rendered":"https:\/\/www.jibsheet.net\/linux\/?p=308"},"modified":"2022-03-25T02:40:17","modified_gmt":"2022-03-25T02:40:17","slug":"python-how-to-construct-and-and-or-with-like","status":"publish","type":"post","link":"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/","title":{"rendered":"Python &#8211; how to construct SQL with &#8220;AND&#8221; and &#8220;OR&#8221; with LIKE"},"content":{"rendered":"<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def run_query_table_multi(  search, and_flag=False ):\r\n        if and_flag is True:\r\n            combo = \" and \"\r\n        else:\r\n            combo = \" or  \"\r\n        try:\r\n                conn = mariadb.connect(\r\n                user=self.user,\r\n                password=self.password,\r\n                host=self.host,\r\n                port=self.port,\r\n                database=self.database\r\n                )\r\n        except mariadb.Error as e:\r\n                print(f\"Error connecting to MariaDB Platform: {e}\", e)\r\n                sys.exit(1)\r\n\r\n            # Get Cursor\r\n        cur = conn.cursor()\r\n\r\n        my_sql_qry = \"SELECT rec_id, title, http from recipe where\"\r\n        q_bld = \"\"\r\n        while len(search) &gt; 0:\r\n            item = search.pop()\r\n            if len(search) &gt; 0:\r\n                q_bld =  q_bld + \"( title like \" +   \"'%\" + item + \"%'\" + \")\" + combo \r\n            else:\r\n                q_bld =  q_bld  + \"( title like \"  +  \"'%\" + item + \"%'\" \")\"\r\n\r\n        try:\r\n            cur.execute(my_sql_qry + q_bld) \r\n        except mariadb.Error as e:\r\n            print(f\"Error: {e}\")\r\n            return None\r\n<\/pre>\n<p>This will result in a query using arbitrary items in a list<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"sql\">run_query_table_multi( [\"Ham', \"Cheese\"], True )\r\n\r\nwill output SQL ===&gt;\r\n\r\n\r\nSELECT rec_id, title, http from recipe where( title like '%Cheese%') and ( title like '%Ham%')\r\n<\/pre>\n<p>Here is how it looks after a bit of refactoring<\/p>\n<p>Used functools filter to get rid of any blanks.\u00a0 \u00a0If you run &#8220;or&#8221; with a blank &#8211; it will select the entire table.<\/p>\n<p>This can support as many as the db can take.<\/p>\n<p>also pass what field you are selection on.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">def build_query(self,  field, psearch, combo):\r\n        like_field = \"( \" + field + \" like \" \r\n        q_bld = \"\"\r\n        psearch = list(filter(None,psearch))\r\n        print(\"qsearch: \", psearch)\r\n        while len(psearch) &gt; 0:\r\n            item = psearch.pop()\r\n            if len(item) &lt; 1:\r\n                continue;\r\n            if len(psearch) &gt; 0:\r\n                q_bld =  q_bld + like_field +   \"'%\" + item + \"%'\" + \")\" + combo \r\n            else:\r\n                q_bld =  q_bld  + like_field   +  \"'%\" + item + \"%'\" \")\"\r\n        return q_bld\r\n<\/pre>\n<p>A sample call<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">my_sql_qry = \"SELECT rec_id, title, http from recipe where\"\r\nfield = \"title\"\r\ncombo = \" and \"\r\n\r\nq_bld = self.build_query(field, psearch, combo)\r\n\r\ntry:\r\n    cur.execute(my_sql_qry + q_bld)          \r\nexcept mariadb.Error as e:\r\n    print(f\"Error: {e}\")\r\n    return None<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>def run_query_table_multi( search, and_flag=False ): if and_flag is True: combo = &#8221; and &#8221; else: combo = &#8221; or &#8221; try: conn = mariadb.connect( user=self.user, password=self.password, host=self.host, port=self.port, database=self.database ) except mariadb.Error as e: print(f&#8221;Error connecting to MariaDB Platform: {e}&#8221;, e) sys.exit(1) # Get Cursor cur = conn.cursor() my_sql_qry = &#8220;SELECT rec_id, title, http from recipe where&#8221; q_bld = &#8220;&#8221; [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[7,27],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v22.4 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Python - how to construct SQL with &quot;AND&quot; and &quot;OR&quot; with LIKE - Jon Allen&#039;s Linux Stuff<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Python - how to construct SQL with &quot;AND&quot; and &quot;OR&quot; with LIKE - Jon Allen&#039;s Linux Stuff\" \/>\n<meta property=\"og:description\" content=\"def run_query_table_multi( search, and_flag=False ): if and_flag is True: combo = &quot; and &quot; else: combo = &quot; or &quot; try: conn = mariadb.connect( user=self.user, password=self.password, host=self.host, port=self.port, database=self.database ) except mariadb.Error as e: print(f&quot;Error connecting to MariaDB Platform: {e}&quot;, e) sys.exit(1) # Get Cursor cur = conn.cursor() my_sql_qry = &quot;SELECT rec_id, title, http from recipe where&quot; q_bld = &quot;&quot; [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/\" \/>\n<meta property=\"og:site_name\" content=\"Jon Allen&#039;s Linux Stuff\" \/>\n<meta property=\"article:published_time\" content=\"2022-03-23T19:12:45+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-03-25T02:40:17+00:00\" \/>\n<meta name=\"author\" content=\"jonallen\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"jonallen\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/\"},\"author\":{\"name\":\"jonallen\",\"@id\":\"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/295a80d0b2aa929b648c4fdddee83993\"},\"headline\":\"Python &#8211; how to construct SQL with &#8220;AND&#8221; and &#8220;OR&#8221; with LIKE\",\"datePublished\":\"2022-03-23T19:12:45+00:00\",\"dateModified\":\"2022-03-25T02:40:17+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/\"},\"wordCount\":81,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/295a80d0b2aa929b648c4fdddee83993\"},\"articleSection\":[\"Python\",\"SQL\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/\",\"url\":\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/\",\"name\":\"Python - how to construct SQL with \\\"AND\\\" and \\\"OR\\\" with LIKE - Jon Allen&#039;s Linux Stuff\",\"isPartOf\":{\"@id\":\"https:\/\/www.jibsheet.net\/linux\/#website\"},\"datePublished\":\"2022-03-23T19:12:45+00:00\",\"dateModified\":\"2022-03-25T02:40:17+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.jibsheet.net\/linux\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Python &#8211; how to construct SQL with &#8220;AND&#8221; and &#8220;OR&#8221; with LIKE\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.jibsheet.net\/linux\/#website\",\"url\":\"https:\/\/www.jibsheet.net\/linux\/\",\"name\":\"Jon Allen's Linux Stuff\",\"description\":\"Howto&#039;s, Observations, and stuff\",\"publisher\":{\"@id\":\"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/295a80d0b2aa929b648c4fdddee83993\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.jibsheet.net\/linux\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/295a80d0b2aa929b648c4fdddee83993\",\"name\":\"jonallen\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/7d7c061ce9db8f5e4710555585475882?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/7d7c061ce9db8f5e4710555585475882?s=96&d=mm&r=g\",\"caption\":\"jonallen\"},\"logo\":{\"@id\":\"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/image\/\"},\"sameAs\":[\"https:\/\/www.jibsheet.net\/linux\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Python - how to construct SQL with \"AND\" and \"OR\" with LIKE - Jon Allen&#039;s Linux Stuff","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/","og_locale":"en_US","og_type":"article","og_title":"Python - how to construct SQL with \"AND\" and \"OR\" with LIKE - Jon Allen&#039;s Linux Stuff","og_description":"def run_query_table_multi( search, and_flag=False ): if and_flag is True: combo = \" and \" else: combo = \" or \" try: conn = mariadb.connect( user=self.user, password=self.password, host=self.host, port=self.port, database=self.database ) except mariadb.Error as e: print(f\"Error connecting to MariaDB Platform: {e}\", e) sys.exit(1) # Get Cursor cur = conn.cursor() my_sql_qry = \"SELECT rec_id, title, http from recipe where\" q_bld = \"\" [&hellip;]","og_url":"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/","og_site_name":"Jon Allen&#039;s Linux Stuff","article_published_time":"2022-03-23T19:12:45+00:00","article_modified_time":"2022-03-25T02:40:17+00:00","author":"jonallen","twitter_card":"summary_large_image","twitter_misc":{"Written by":"jonallen","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/#article","isPartOf":{"@id":"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/"},"author":{"name":"jonallen","@id":"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/295a80d0b2aa929b648c4fdddee83993"},"headline":"Python &#8211; how to construct SQL with &#8220;AND&#8221; and &#8220;OR&#8221; with LIKE","datePublished":"2022-03-23T19:12:45+00:00","dateModified":"2022-03-25T02:40:17+00:00","mainEntityOfPage":{"@id":"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/"},"wordCount":81,"commentCount":0,"publisher":{"@id":"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/295a80d0b2aa929b648c4fdddee83993"},"articleSection":["Python","SQL"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/","url":"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/","name":"Python - how to construct SQL with \"AND\" and \"OR\" with LIKE - Jon Allen&#039;s Linux Stuff","isPartOf":{"@id":"https:\/\/www.jibsheet.net\/linux\/#website"},"datePublished":"2022-03-23T19:12:45+00:00","dateModified":"2022-03-25T02:40:17+00:00","breadcrumb":{"@id":"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.jibsheet.net\/linux\/index.php\/2022\/03\/23\/python-how-to-construct-and-and-or-with-like\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.jibsheet.net\/linux\/"},{"@type":"ListItem","position":2,"name":"Python &#8211; how to construct SQL with &#8220;AND&#8221; and &#8220;OR&#8221; with LIKE"}]},{"@type":"WebSite","@id":"https:\/\/www.jibsheet.net\/linux\/#website","url":"https:\/\/www.jibsheet.net\/linux\/","name":"Jon Allen's Linux Stuff","description":"Howto&#039;s, Observations, and stuff","publisher":{"@id":"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/295a80d0b2aa929b648c4fdddee83993"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.jibsheet.net\/linux\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/295a80d0b2aa929b648c4fdddee83993","name":"jonallen","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/7d7c061ce9db8f5e4710555585475882?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/7d7c061ce9db8f5e4710555585475882?s=96&d=mm&r=g","caption":"jonallen"},"logo":{"@id":"https:\/\/www.jibsheet.net\/linux\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/www.jibsheet.net\/linux"]}]}},"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/www.jibsheet.net\/linux\/index.php\/wp-json\/wp\/v2\/posts\/308"}],"collection":[{"href":"https:\/\/www.jibsheet.net\/linux\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.jibsheet.net\/linux\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.jibsheet.net\/linux\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.jibsheet.net\/linux\/index.php\/wp-json\/wp\/v2\/comments?post=308"}],"version-history":[{"count":5,"href":"https:\/\/www.jibsheet.net\/linux\/index.php\/wp-json\/wp\/v2\/posts\/308\/revisions"}],"predecessor-version":[{"id":314,"href":"https:\/\/www.jibsheet.net\/linux\/index.php\/wp-json\/wp\/v2\/posts\/308\/revisions\/314"}],"wp:attachment":[{"href":"https:\/\/www.jibsheet.net\/linux\/index.php\/wp-json\/wp\/v2\/media?parent=308"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.jibsheet.net\/linux\/index.php\/wp-json\/wp\/v2\/categories?post=308"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.jibsheet.net\/linux\/index.php\/wp-json\/wp\/v2\/tags?post=308"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}