{"id":126099,"date":"2022-06-29T16:28:54","date_gmt":"2022-06-29T16:28:54","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=439312"},"modified":"2022-06-29T16:28:54","modified_gmt":"2022-06-29T16:28:54","slug":"how-to-use-a-list-as-an-sqlite-parameter-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/06\/29\/how-to-use-a-list-as-an-sqlite-parameter-in-python\/","title":{"rendered":"How to use a List as an SQLite Parameter in Python"},"content":{"rendered":"<div class=\"kk-star-ratings kksr-valign-top kksr-align-left \" data-payload=\"{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;439312&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<h2 class=\"wp-embed-aspect-16-9 wp-has-aspect-ratio\">Problem Formulation and Solution Overview<\/h2>\n<p><em>This article works with the fictitious Finxter database to retrieve three (3) specific users, via a SQLite query using the IN command. <\/em><\/p>\n<p><em>To follow along, <a rel=\"noreferrer noopener\" href=\"https:\/\/drive.google.com\/file\/d\/1Gf1bJfuUNdbupYM06QU1zSezTZinxvp0\/view?usp=sharing\" data-type=\"URL\" data-id=\"https:\/\/drive.google.com\/file\/d\/1Gf1bJfuUNdbupYM06QU1zSezTZinxvp0\/view?usp=sharing\" target=\"_blank\">click <\/a><a href=\"https:\/\/drive.google.com\/file\/d\/1Gf1bJfuUNdbupYM06QU1zSezTZinxvp0\/view?usp=sharing\" data-type=\"URL\" data-id=\"https:\/\/drive.google.com\/file\/d\/1Gf1bJfuUNdbupYM06QU1zSezTZinxvp0\/view?usp=sharing\" target=\"_blank\" rel=\"noreferrer noopener\">here <\/a>to download this file and move it into the current working directory.<\/em><\/p>\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n<h2>Preparation<\/h2>\n<p>Add the following code to the top of the code snippet. This snippet will allow the code in this article to run error-free.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import sqlite3<\/pre>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><strong>Note:<\/strong> The <a rel=\"noreferrer noopener\" href=\"https:\/\/docs.python.org\/3\/library\/sqlite3.html\" data-type=\"URL\" data-id=\"https:\/\/docs.python.org\/3\/library\/sqlite3.html\" target=\"_blank\">S<\/a><a rel=\"noreferrer noopener\" href=\"https:\/\/docs.python.org\/3\/library\/sqlite3.html\" data-type=\"URL\" data-id=\"https:\/\/docs.python.org\/3\/library\/sqlite3.html\" target=\"_blank\">Q<\/a><a rel=\"noreferrer noopener\" href=\"https:\/\/docs.python.org\/3\/library\/sqlite3.html\" data-type=\"URL\" data-id=\"https:\/\/docs.python.org\/3\/library\/sqlite3.html\" target=\"_blank\">L<\/a><a rel=\"noreferrer noopener\" href=\"https:\/\/docs.python.org\/3\/library\/sqlite3.html\" data-type=\"URL\" data-id=\"https:\/\/docs.python.org\/3\/library\/sqlite3.html\" target=\"_blank\">ite<\/a> library is built into Python and does not need to be installed but must be referenced.<\/p>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n<h2>Overview<\/h2>\n<p>The <code>Finxter<\/code> database file contains 25 records in <code><a href=\"https:\/\/blog.finxter.com\/the-ultimate-guide-to-python-tuples\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/the-ultimate-guide-to-python-tuples\/\">tuple<\/a><\/code> format. Below is a snippet from this file.<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><code>(30022145, 'Steve', 'Hamilton', 'Authority')<br \/>(30022192, 'Amy', 'Pullister', 'Beginner')<br \/>(30022331, 'Peter', 'Dunn', 'Basic Knowledge')<br \/>(30022345, 'Marcus', 'Williams', 'Experienced Learner')<br \/>(30022359, 'Alice', 'Miller', 'Authority')<br \/>(30022361, 'Craig', 'Driver', 'Autodidact')<br \/>...<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>The structure of the <code>users <\/code>table is as follows:<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><strong>DATA TYPE<\/strong><\/td>\n<td><strong>FIELD NAME<\/strong><\/td>\n<\/tr>\n<tr>\n<td>INTEGER<\/td>\n<td>FID<\/td>\n<\/tr>\n<tr>\n<td>TEXT<\/td>\n<td>First_Name<\/td>\n<\/tr>\n<tr>\n<td>TEXT<\/td>\n<td>Last_Name<\/td>\n<\/tr>\n<tr>\n<td>TEXT<\/td>\n<td>Rank<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>Now that the overview is complete, let&#8217;s connect to the database, filter, and output the results.<\/p>\n<hr class=\"wp-block-separator has-css-opacity\" \/>\n<h2>Connect to a SQLite Database <\/h2>\n<p class=\"has-global-color-8-background-color has-background\">This code connects to an SQLite database and is placed inside a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-catch-and-print-exception-messages-in-python\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/how-to-catch-and-print-exception-messages-in-python\/\" target=\"_blank\">try\/except<\/a> statement to catch any possible errors.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"2-3\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">try: conn = sqlite3.connect('finxter_users.db') cur = conn.cursor() except Exception as e: print(f'An error occurred: {e}.') exit()<\/pre>\n<p>The code inside the <code>try<\/code> statement executes first and attempts to connect to <code>finxter_users.db<\/code>. A <em>Connection Object<\/em> (<code>conn<\/code>), similar to below, is produced, if successful.<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><code>&lt;sqlite3.Connection object at 0x00000194FFBC2140&gt;<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>Next, the <em>Connection Object<\/em> created above (<code>conn<\/code>) is used in conjunction with the <code>cursor()<\/code> to create a <em>Cursor Object<\/em>. A Cursor Object (<code>cur<\/code>), similar to below, is produced, if successful.<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><code>&lt;sqlite3.Cursor object at 0x0000022750E5CCC0&gt;<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><strong>Note: <\/strong>The <em>Cursor Object<\/em> allows interaction with database specifics, such as executing queries.<\/p>\n<p>If the above line(s) fail, the code falls inside <code>except<\/code> capturing the error (<code>e<\/code>) and outputs this to the terminal. Code execution halts.<\/p>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n<h2>Prepare the SQLite Query<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">Before executing any query, you must decide the expected results and how to achieve this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"5-7\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">try: conn = sqlite3.connect('finxter_users.db') cur = conn.cursor() fid_list = [30022192, 30022450, 30022475] fid_tuple = tuple(fid_list) f_query = f'SELECT * FROM users WHERE FID IN {format(fid_tuple)}' except Exception as e: print(f'An error occurred: {e}.') exit()<\/pre>\n<p>In this example, the three (3) highlighted lines create, configure and save the following variables:<\/p>\n<ul>\n<li><code><strong>fid_list<\/strong><\/code>: this contains a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-lists\/\" target=\"_blank\"><code>list<\/code><\/a> of the selected <em>Users&#8217;<\/em> <em>FIDs <\/em>to retrieve.<\/li>\n<li><code><strong>fid_tuple<\/strong><\/code>: this converts <code>fid_list <\/code>into a <code><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/the-ultimate-guide-to-python-tuples\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/the-ultimate-guide-to-python-tuples\/\" target=\"_blank\">tuple<\/a><\/code> format. This is done to match the database format (see above).<\/li>\n<li><code><strong>f_query<\/strong><\/code>: this constructs an SQLite query that returns all matching records when executed.<\/li>\n<\/ul>\n<p><strong>Query String Output<\/strong><\/p>\n<p>If <code>f_query<\/code> was output to the terminal (<code>print(<code>f_query<\/code>)<\/code>), the following would display. Perfect! That&#8217;s exactly what we want.<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><code> SELECT * FROM users WHERE FID IN (30022192, 30022450, 30022475)<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n<h2>Executing the SQLite Query<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">Let&#8217;s execute the query created above and save the results.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"8\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">try: conn = sqlite3.connect('finxter_users.db') cur = conn.cursor() fid_list = [30022192, 30022450, 30022475] fid_tuple = tuple(fid_list) f_query = f'SELECT * FROM users WHERE FID IN {format(fid_tuple)}' results = cur.execute(f_query)\nexcept Exception as e: print(f'An error occurred: {e}.') exit()<\/pre>\n<p>The highlighted line appends the <a rel=\"noreferrer noopener\" href=\"https:\/\/docs.python.org\/3\/library\/sqlite3.html\" data-type=\"URL\" data-id=\"https:\/\/docs.python.org\/3\/library\/sqlite3.html\" target=\"_blank\"><code>execute()<\/code><\/a> method to the <em>Cursor Objec<\/em>t and passes the <code>f_query<\/code> string as an argument.<\/p>\n<p>If the execution was successful, an <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/iterators-iterables-and-itertools\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/iterators-iterables-and-itertools\/\" target=\"_blank\">iterable<\/a> <em>Cursor Object<\/em> is produced, similar to below.<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><code> &lt;sqlite3.Cursor object at 0x00000224FF987A40&gt;<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n<h2>Displaying the Query Results<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">The standard way to display the query results is by using a <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-loops\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/python-loops\/\" target=\"_blank\"><code>for<\/code><\/a> a loop.<br \/>We could add this loop inside\/outside the<a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-catch-and-print-exception-messages-in-python\/\" data-type=\"URL\" data-id=\"https:\/\/blog.finxter.com\/how-to-catch-and-print-exception-messages-in-python\/\" target=\"_blank\"> try\/except<\/a> statement.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"13-15\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">try: conn = sqlite3.connect('finxter_users.db') cur = conn.cursor() fid_list = [30022192, 30022450, 30022475] fid_tuple = tuple(fid_list) f_query = f'SELECT * FROM users WHERE FID IN {format(fid_tuple)}' results = cur.execute(f_query)\nexcept Exception as e: print(f'An error occurred: {e}.') exit() for r in results: print(r)\nconn.close()<\/pre>\n<p>The highlighted lines instantiate a for loop to navigate the query results one record at a time and output them to the terminal.<\/p>\n<p><strong>Query Results<\/strong><\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><code>(30022192, 'Amy', 'Pullister', 'Beginner')<br \/>(30022450, 'Leon', 'Garcia', 'Authority')<br \/>(30022475, 'Isla', 'Jackson', 'Scholar')<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>Finally, the <em>Connection Object<\/em> created earlier needs to be closed.<\/p>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n<h2>Summary<\/h2>\n<p>In this article you learned how to:<\/p>\n<ul>\n<li>Create a Connection Object.<\/li>\n<li>Create a Cursor Object.<\/li>\n<li>Construct and Execute a SQLite Query.<\/li>\n<li>Output the results to the terminal.<\/li>\n<\/ul>\n<p>We hope you enjoyed this article.<\/p>\n<p>Happy Coding!<\/p>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n<h2>Programmer Humor<\/h2>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f471-200d-2640-fe0f.png\" alt=\"\ud83d\udc71\u200d\u2640\ufe0f\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Programmer 1<\/strong>: We have a problem<br \/><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f9d4-200d-2642-fe0f.png\" alt=\"\ud83e\uddd4\u200d\u2642\ufe0f\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Programmer 2<\/strong>: Let\u2019s use RegEx!<br \/><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f471-200d-2640-fe0f.png\" alt=\"\ud83d\udc71\u200d\u2640\ufe0f\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Programmer 1<\/strong>: Now we have two problems<\/p>\n<p>&#8230; yet &#8211; you can easily reduce the two problems to zero as you polish your &#8220;<a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-regex\/\" data-type=\"post\" data-id=\"6210\" target=\"_blank\">RegEx Superpower in Python<\/a>&#8220;. <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f642.png\" alt=\"\ud83d\ude42\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) Problem Formulation and Solution Overview This article works with the fictitious Finxter database to retrieve three (3) specific users, via a SQLite query using the IN command. To follow along, click here to download this file and move it into the current working directory. Preparation Add the following code to the [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-126099","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/126099","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=126099"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/126099\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=126099"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=126099"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=126099"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}