<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python &#187; Database</title>
	<atom:link href="/python/category/database/feed/" rel="self" type="application/rss+xml" />
	<link>https://talkera.org/python</link>
	<description>Programming Blog</description>
	<lastBuildDate>Sun, 01 Feb 2015 17:15:10 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1</generator>
	<item>
		<title>Python Database Programming: SQLite (tutorial)</title>
		<link>https://talkera.org/python/python-database-programming-sqlite-tutorial/</link>
		<comments>https://talkera.org/python/python-database-programming-sqlite-tutorial/#comments</comments>
		<pubDate>Sun, 01 Feb 2015 17:15:10 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[RDBMS]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=123</guid>
		<description><![CDATA[In this tutorial you will learn how to use the SQLite database management system with Python.  You will learn how to use SQLite, SQL queries, RDBMS and more of this cool stuff! Data is everywhere and software applications use that. Data is either in memory, files or databases. One of these database management systems (DBMS) [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In this tutorial you will learn how to use the SQLite database management system with Python.  You will learn how to use SQLite, SQL queries, RDBMS and more of this cool stuff!</p>
<p>Data is everywhere and software applications use that. Data is either in memory, files or databases. One of these database management systems (DBMS) is called SQLite.  SQLite was created in the year 2000 for a missile control system (boom! did we say it was cool?) and is one of the many management systems in the database zoo. MySQL, Postregsql, Oracle, Microsoft SQL Server and Maria DB are other database animals in this zoo.  So what is this <em>SQL</em>?</p>
<p>SQL is a special-purpose programming language designed for managing data held in a databases. The language has been around since 1986 and is worth learning. The video below is an old funny video about SQL.</p>
<p><iframe width="580" height="435" src="https://www.youtube.com/embed/5ycx9hFGHog?feature=oembed" frameborder="0" allowfullscreen></iframe></p>
<p>Why use SQLite? SQLite is the most widely deployed SQL database engine in the world. The source code for SQLite is in the public domain. It is a self-contained, serverless, zero-configuration, transactional SQL database engine. The SQLite project is sponsored by Bloomberg and Mozilla.</p>
<p><strong>Installation:</strong></p><pre class="crayon-plain-tag">$ sudo apt-get install sqlite</pre><p>Verify if it is correctly installed. Copy this program and save it as test1.py</p><pre class="crayon-plain-tag">#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = None

try:
    con = lite.connect('test.db')
    cur = con.cursor()    
    cur.execute('SELECT SQLITE_VERSION()')
    data = cur.fetchone()
    print "SQLite version: %s" % data                
except lite.Error, e:   
    print "Error %s:" % e.args[0]
    sys.exit(1)
finally:    
    if con:
        con.close()</pre><p>Execute with:</p><pre class="crayon-plain-tag">$ python test1.py</pre><p>It should output:</p><pre class="crayon-plain-tag">SQLite version: 3.8.2</pre><p><strong>What did the script above do?</strong><br />
The script connected to a new database called test.db with this line:</p><pre class="crayon-plain-tag">con = lite.connect('test.db')</pre><p>It then queries the database management system with the command</p><pre class="crayon-plain-tag">SELECT SQLITE_VERSION()</pre><p>which in turn returned its version number. That line is known as an SQL query.</p>
<div id="attachment_139" style="width: 607px" class="wp-caption alignnone"><a href="/python/wp-content/uploads/2015/02/db.png"><img class="wp-image-139 size-full" src="/python/wp-content/uploads/2015/02/db.png" alt="SQL joke. From Reddit" width="597" height="181" /></a><p class="wp-caption-text">SQL joke. Source: Reddit</p></div>
<p><strong>Storing data</strong><br />
The script below will store data into a new database called user.db</p><pre class="crayon-plain-tag">#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = lite.connect('user.db')

with con:
    
    cur = con.cursor()    
    cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
    cur.execute("INSERT INTO Users VALUES(1,'Michelle')")
    cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
    cur.execute("INSERT INTO Users VALUES(3,'Greg')")</pre><p>SQLite is a database management system that uses tables. These tables can have relations with other tables: it&#8217;s called relational database management system or RDBMS.  The table defines the structure of the data and can hold the data.  A database can hold many different tables. The table gets created using the command:</p><pre class="crayon-plain-tag">cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")</pre><p>We add  records into the table with these commands:</p><pre class="crayon-plain-tag">cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
    cur.execute("INSERT INTO Users VALUES(3,'Greg')")</pre><p>The first value is the ID. The second value is the name.  Once we run the script the data gets inserted into the database table Users:</p>
<p><a href="/python/wp-content/uploads/2015/02/table21.png"><img class="alignnone wp-image-153 size-full" src="/python/wp-content/uploads/2015/02/table21.png" alt="table2" width="335" height="106" /></a></p>
<p><strong>Exploring the data</strong><br />
We can explore the database using two methods:  the command line and a graphical interface.</p>
<p><em>From console:</em> To explore using the command line type these commands:</p><pre class="crayon-plain-tag">sqlite3 user.db
.tables
SELECT * FROM Users;</pre><p>This will output the data in the table Users.</p><pre class="crayon-plain-tag">sqlite&gt; SELECT * FROM Users;
1|Michelle
2|Sonya
3|Greg</pre><p><em>From GUI:</em> If you want to use a GUI instead, there is a lot of choice. Personally I picked sqllite-man but there are <a href="https://stackoverflow.com/questions/835069/which-sqlite-administration-console-do-you-recommend" target="_blank">many others</a>. We install using:</p><pre class="crayon-plain-tag">sudo apt-get install sqliteman</pre><p>We start the application sqliteman. A gui pops up.</p>
<p><a href="/python/wp-content/uploads/2015/02/sqliteman.png"><img class="alignnone wp-image-134 size-full" src="/python/wp-content/uploads/2015/02/sqliteman.png" alt="sqliteman" width="668" height="661" /></a></p>
<p>Press File &gt; Open &gt; user.db.  It appears like not much has changed, do not worry, this is just the user interface.  On the left is a small tree view, press Tables &gt; users. The full table including all records will be showing now.</p>
<p><a href="/python/wp-content/uploads/2015/02/sqliteman2.png"><img class="alignnone wp-image-135 size-full" src="/python/wp-content/uploads/2015/02/sqliteman2.png" alt="sqliteman2" width="668" height="661" /></a></p>
<p>This GUI can be used to modify the records (data) in the table and to add new tables.</p>
<p><strong> The SQL language</strong><br />
SQL has many commands to interact with the database. You can try the commands below from the command line or from the GUI:</p><pre class="crayon-plain-tag">sqlite3 user.db 
SELECT * FROM Users;
SELECT count(*) FROM Users;
SELECT name FROM Users;
SELECT * FROM Users WHERE id = 2;
DELETE FROM Users WHERE id = 6;</pre><p>We can use those queries in a Python program:</p><pre class="crayon-plain-tag">#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys


con = lite.connect('user.db')

with con:    
    
    cur = con.cursor()    
    cur.execute("SELECT * FROM Users")

    rows = cur.fetchall()

    for row in rows:
        print row</pre><p>This will output all data in the Users table from the database:</p><pre class="crayon-plain-tag">$ python get.py 
(1, u'Michelle')
(2, u'Sonya')
(3, u'Greg')</pre><p>&nbsp;</p>
<div id="attachment_174" style="width: 650px" class="wp-caption alignnone"><a href="/python/wp-content/uploads/2015/02/joke.jpg"><img class="wp-image-174 size-full" src="/python/wp-content/uploads/2015/02/joke.jpg" alt="SQL joke. Source: flickr" width="640" height="426" /></a><p class="wp-caption-text">SQL joke. Source: flickr</p></div>
<p><strong>Creating a user information database</strong><br />
We can structure our data across multiple tables. This keeps our data structured, fast and organized.  If we would have a single table to store everything, we would quickly have a big chaotic mess. What we will do is create multiple tables and use them in a combination. We create two tables:</p>
<p><em>Users:</em></p>
<p><a href="/python/wp-content/uploads/2015/02/t1.png"><img class="alignnone wp-image-165 size-full" src="/python/wp-content/uploads/2015/02/t1.png" alt="t1" width="514" height="102" /></a></p>
<p><em>Jobs:</em></p>
<p><a href="/python/wp-content/uploads/2015/02/t2.png"><img class="alignnone wp-image-166 size-full" src="/python/wp-content/uploads/2015/02/t2.png" alt="t2" width="514" height="100" /></a></p>
<p>To create these tables, you can do that by hand in the GUI or use the script below:</p><pre class="crayon-plain-tag"># -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
 
con = lite.connect('system.db')
 
with con:
    
    cur = con.cursor()    
    cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
    cur.execute("INSERT INTO Users VALUES(1,'Michelle')")
    cur.execute("INSERT INTO Users VALUES(2,'Howard')")
    cur.execute("INSERT INTO Users VALUES(3,'Greg')")

    cur.execute("CREATE TABLE Jobs(Id INT, Uid INT, Profession TEXT)")
    cur.execute("INSERT INTO Jobs VALUES(1,1,'Scientist')")
    cur.execute("INSERT INTO Jobs VALUES(2,2,'Marketeer')")
    cur.execute("INSERT INTO Jobs VALUES(3,3,'Developer')")</pre><p>The jobs table has an extra parameter, Uid. We use that to connect the two tables in an SQL query:</p><pre class="crayon-plain-tag">SELECT users.name, jobs.profession FROM jobs INNER JOIN users ON users.ID = jobs.uid</pre><p>You can incorporate that SQL query in a Python script:</p><pre class="crayon-plain-tag">#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys


con = lite.connect('system.db')

with con:    
    
    cur = con.cursor()    
    cur.execute("SELECT users.name, jobs.profession FROM jobs INNER JOIN users ON users.ID = jobs.uid")

    rows = cur.fetchall()

    for row in rows:
        print row</pre><p>It should output:</p><pre class="crayon-plain-tag">$ python get2.py
(u'Michelle', u'Scientist')
(u'Howard', u'Marketeer')
(u'Greg', u'Developer')</pre><p>If you liked this tutorial please share it using one of the buttons below <img src="/python/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley" /></p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;title=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" id="wpa2a_2"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/python-database-programming-sqlite-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
