{"id":33,"date":"2022-02-27T20:01:44","date_gmt":"2022-02-27T20:01:44","guid":{"rendered":"https:\/\/sonic.fabio.org.uk\/?p=33"},"modified":"2022-02-27T22:02:23","modified_gmt":"2022-02-27T22:02:23","slug":"sqlite-in-python","status":"publish","type":"post","link":"https:\/\/sonic.fabio.org.uk\/?p=33","title":{"rendered":"SQLite in Python"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Getting started<\/h2>\n\n\n\n<p>SQLite is a common SQL database engine. In this blog, I will go over how you can connect and query a SQLite database in Python.<\/p>\n\n\n\n<p>Let&#8217;s import the necessary libraries for this example, and establish a connection to a database. We will be using the <code class=\"\" data-line=\"\">sqlite3 <\/code>library and <code class=\"\" data-line=\"\">pandas<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"\" data-line=\"\">import sqlite3\nimport pandas as pd\nconn = sqlite3.connect(&#039;supermarket.db&#039;) # connect to a supermarket database<\/code><\/pre>\n\n\n\n<p>To execute SQL commands, we need to create a cursor object. Let&#8217;s use the cursor to create a table called <em>shops <\/em>which will contain basic information about our supermarket stores (shop ID, size, postcode) . The store sizes are small, medium and large.<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"\" data-line=\"\">cursor = conn.cursor() # create a cursor\ncursor.execute(&quot;CREATE TABLE shops(shopid VARCHAR(100) PRIMARY KEY, Store_size VARCHAR(30), Postcode VARCHAR(8))&quot;)<\/code><\/pre>\n\n\n\n<p>So, <code class=\"\" data-line=\"\">cursor.execute()<\/code> executes SQL commands.<\/p>\n\n\n\n<p>We can insert data into the table using the <code class=\"\" data-line=\"\">INSERT<\/code> command. If we do this, use <code class=\"\" data-line=\"\">conn.commit()<\/code> to save the data to the table.<\/p>\n\n\n\n<p>However, in this example, we have a <code class=\"\" data-line=\"\">pandas<\/code> DataFrame called <code class=\"\" data-line=\"\">shops_df<\/code> that we wish to insert into our SQL table called <code class=\"\" data-line=\"\">shops<\/code>. It has the same columns as our <code class=\"\" data-line=\"\">shops<\/code> table. If you&#8217;re more familiar with pandas than SQL like me, I will use pandas to clean data first. Only after this will I want to store the data in an SQL database.<\/p>\n\n\n\n<p>The<code class=\"\" data-line=\"\"> to_sql() <\/code>function allows us to write records in a DataFrame to an SQL database.<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"\" data-line=\"\">shops_df.to_sql(&#039;shops&#039;, conn, if_exists=&#039;append&#039;, index=False) # write shops_df to shops table<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Queries<\/h2>\n\n\n\n<p>The cursor behaves like an iterator object. We can use a <em>for loop<\/em> to retrieve all rows from a SELECT statement. To make it easier to query in future, I&#8217;ll create a query function.<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"\" data-line=\"\">def query(q):\n    try:\n        for row in cursor.execute(q):\n            print(row)\n    except Exception as e:\n        print(&quot;Something went wrong... &quot;, e)\n\nquery(&#039;SELECT * FROM shops&#039;)<\/code><\/pre>\n\n\n\n<p>We can also save the results of a query by assigning it to a variable. The variable will be a list of tuples. A tuple for each row.<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"\" data-line=\"\">q=&quot;SELECT shopid, Postcode FROM shops&quot;\nquery_results = cursor.execute(q).fetchall() # save results as a list of tuples<\/code><\/pre>\n\n\n\n<p>Storing results from a query like this can allow you to represent table data with graphs. For example, if you had a table called <code class=\"\" data-line=\"\">sales<\/code> in your database which has the shop profits, you could plot trends in sales. I will illustrate this now.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/sonic.fabio.org.uk\/wp-content\/uploads\/2022\/02\/Screenshot-2022-02-27-192048.png\" alt=\"\" class=\"wp-image-35\" width=\"176\" height=\"156\"\/><figcaption>Above: A preview of the sales table which is in our SQLite database already<\/figcaption><\/figure>\n\n\n\n<p>Let&#8217;s query the minimum, mean and maximum yearly sales&#8230;<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"\" data-line=\"\">c=&quot;&quot;&quot;\nSELECT shops.Store_size, sales.Year, MIN(sales.Sales), AVG(sales.Sales), MAX(sales.Sales)\nFROM shops\nJOIN sales\n  ON shops.shopid = sales.shopid\nGROUP BY shops.Store_size, sales.Year \n&quot;&quot;&quot;\nquery(c)\nresult = cursor.execute(c).fetchall()<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"367\" height=\"468\" src=\"https:\/\/sonic.fabio.org.uk\/wp-content\/uploads\/2022\/02\/Screenshot-2022-02-27-192838.png\" alt=\"\" class=\"wp-image-37\" srcset=\"https:\/\/sonic.fabio.org.uk\/wp-content\/uploads\/2022\/02\/Screenshot-2022-02-27-192838.png 367w, https:\/\/sonic.fabio.org.uk\/wp-content\/uploads\/2022\/02\/Screenshot-2022-02-27-192838-235x300.png 235w\" sizes=\"(max-width: 367px) 100vw, 367px\" \/><figcaption>Above: the results from our query<\/figcaption><\/figure>\n\n\n\n<p>&#8230;next I plot the mean sales for medium sized stores against the year&#8230;<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"\" data-line=\"\">years=[] # store the year\nmeans = [] # store the mean sales\nsize = &#039;medium&#039;\nfor results in result:\n    if results[0] == size:\n        means.append(results[3])\n        years.append(results[1])\n\nplt.plot(years, means, linestyle = &#039;dashed&#039;, marker = &#039;o&#039;, ms= &#039;5&#039;)\nplt.title(f&quot;{size} store mean sales&quot;)\nplt.xlabel(&quot;year&quot;)\nplt.ylabel(&quot;sales&quot;)\nplt.savefig(f&quot;{size}_store_mean_sales.png&quot;)\nplt.show()<\/code><\/pre>\n\n\n\n<figure class=\"wp-block-image size-full is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/sonic.fabio.org.uk\/wp-content\/uploads\/2022\/02\/medium_store_mean_sales.png\" alt=\"\" class=\"wp-image-38\" width=\"459\" height=\"306\" srcset=\"https:\/\/sonic.fabio.org.uk\/wp-content\/uploads\/2022\/02\/medium_store_mean_sales.png 432w, https:\/\/sonic.fabio.org.uk\/wp-content\/uploads\/2022\/02\/medium_store_mean_sales-300x200.png 300w\" sizes=\"(max-width: 459px) 100vw, 459px\" \/><figcaption>Above: the mean sales for stores that are medium sized<\/figcaption><\/figure>\n\n\n\n<p>Now we are done, close the connection to the database.<\/p>\n\n\n\n<pre class=\"wp-block-prismatic-blocks\"><code class=\"\" data-line=\"\">conn.close() # don&#039;t forget to close the connection afterwards<\/code><\/pre>\n\n\n\n<p>I hope this blog was helpful for getting started with the sqlite3 library, to connect to a database, and use a cursor to execute SQL commands in python.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Getting started SQLite is a common SQL database engine. In this blog, I will go over how you can connect and query a SQLite database in Python. Let&#8217;s import the necessary libraries for this example, and establish a connection to a database. We will be using the sqlite3 library and pandas. To execute SQL commands, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[8,12],"tags":[11,10],"_links":{"self":[{"href":"https:\/\/sonic.fabio.org.uk\/index.php?rest_route=\/wp\/v2\/posts\/33"}],"collection":[{"href":"https:\/\/sonic.fabio.org.uk\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sonic.fabio.org.uk\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sonic.fabio.org.uk\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sonic.fabio.org.uk\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=33"}],"version-history":[{"count":8,"href":"https:\/\/sonic.fabio.org.uk\/index.php?rest_route=\/wp\/v2\/posts\/33\/revisions"}],"predecessor-version":[{"id":48,"href":"https:\/\/sonic.fabio.org.uk\/index.php?rest_route=\/wp\/v2\/posts\/33\/revisions\/48"}],"wp:attachment":[{"href":"https:\/\/sonic.fabio.org.uk\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=33"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sonic.fabio.org.uk\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=33"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sonic.fabio.org.uk\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=33"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}