Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
For 2021 - online Python 3 training - see ((here)).

Our plans were to retire in summer 2020 and see the world, but Coronavirus has lead us into a lot of lockdown programming in Python 3 and PHP 7.
We can now offer tailored online training - small groups, real tutors - works really well for groups of 4 to 14 delegates. Anywhere in the world; course language English.

Please ask about private 'maintenance' training for Python 2, Tcl, Perl, PHP, Lua, etc.
sqlite3 - connect, create, insert, select
Python and SQL databases example from a Well House Consultants training course
More on Python and SQL databases [link]

This example is described in the following article(s):
   • SQL databases from Python - an SQLite example - [link]
   • Accessing a MySQL database from Python with mysql.connector - [link]

Source code: databases_python Module: Y113
import sqlite3
import sys

# Create an example database and table ...

timespend=2

if len(sys.argv) > 1:
    if sys.argv[1] == "seed":
        conn = sqlite3.connect('mysample.db') # name of the file to hold the database

        c = conn.cursor()
        c.execute("CREATE TABLE course (cid int, name text, days int)")
        c.execute('INSERT INTO course VALUES(1,"Python Programming",3)')
        c.execute('INSERT INTO course VALUES(2,"Intermediate Python",3)')
        c.execute('INSERT INTO course VALUES(3,"Feeding your Python",2)')
        conn.commit()

        c = conn.cursor()
        c.execute("CREATE TABLE endday (eid int, dayname text)")
        c.execute('INSERT INTO endday VALUES(1,"Monday")')
        c.execute('INSERT INTO endday VALUES(2,"Tuesday")')
        c.execute('INSERT INTO endday VALUES(3,"Wednesday")')
        c.execute('INSERT INTO endday VALUES(4,"Thursday")')
        c.execute('INSERT INTO endday VALUES(5,"Friday")')
        conn.commit()
    else:
        timespend = int(sys.argv[1])

# Then - (default use) use the data

conn = sqlite3.connect('mysample.db') # name of the file to hold the database
c = conn.cursor()

print "Sample select using a program generated query"
rows = 0
gimme = c.execute("SELECT name, days FROM course WHERE days > " + str(timespend))
for gotme in gimme:
        print gotme
        rows += 1
print "Total of",rows,"records selected"

print "Sample select using a join of 2 tables"
rows = 0
gimme = c.execute("SELECT name, days FROM course WHERE days > " + str(timespend))
gimme = c.execute("SELECT * FROM course JOIN endday ON days = eid")
for gotme in gimme:
        print gotme
        rows += 1
print "Total of",rows,"records selected"

""" Samples of that running:

Accessing the tables when they don't exist (error condition test)

munchkin:pf13 grahamellis$ python databases_python
Sample select using a program generated query
Traceback (most recent call last):
  File "databases_python", line 38, in <module>
    gimme = c.execute("SELECT name, days FROM course WHERE days > " + str(timespend))
sqlite3.OperationalError: no such table: course

Seeding the tables and reporting on what was added

munchkin:pf13 grahamellis$ python databases_python seed
Sample select using a program generated query
(u'Python Programming', 3)
(u'Intermediate Python', 3)
Total of 2 records selected
Sample select using a join of 2 tables
(1, u'Python Programming', 3, 3, u'Wednesday')
(2, u'Intermediate Python', 3, 3, u'Wednesday')
(3, u'Feeding your Python', 2, 2, u'Tuesday')
Total of 3 records selected

Accessing the tables - courses of longer than one day

munchkin:pf13 grahamellis$ python databases_python 1
Sample select using a program generated query
(u'Python Programming', 3)
(u'Intermediate Python', 3)
(u'Feeding your Python', 2)
Total of 3 records selected
Sample select using a join of 2 tables
(1, u'Python Programming', 3, 3, u'Wednesday')
(2, u'Intermediate Python', 3, 3, u'Wednesday')
(3, u'Feeding your Python', 2, 2, u'Tuesday')
Total of 3 records selected

Accessing the tables - courses of longer than three daya

munchkin:pf13 grahamellis$ python databases_python 3
Sample select using a program generated query
Total of 0 records selected
Sample select using a join of 2 tables
(1, u'Python Programming', 3, 3, u'Wednesday')
(2, u'Intermediate Python', 3, 3, u'Wednesday')
(3, u'Feeding your Python', 2, 2, u'Tuesday')
Total of 3 records selected

Accessing the tables - courses of longer than two daya

munchkin:pf13 grahamellis$ python databases_python 2
Sample select using a program generated query
(u'Python Programming', 3)
(u'Intermediate Python', 3)
Total of 2 records selected
Sample select using a join of 2 tables
(1, u'Python Programming', 3, 3, u'Wednesday')
(2, u'Intermediate Python', 3, 3, u'Wednesday')
(3, u'Feeding your Python', 2, 2, u'Tuesday')
Total of 3 records selected

Try creating tables that already exist - ensuring error is generated

munchkin:pf13 grahamellis$ python databases_python seed
Traceback (most recent call last):
  File "databases_python", line 14, in <module>
    c.execute("CREATE TABLE course (cid int, name text, days int)")
sqlite3.OperationalError: table course already exists
munchkin:pf13 grahamellis$

"""

Learn about this subject
This module and example are covered on the following public courses:
 * Learning to program in Python
 * Python Programming
Also available on on site courses for larger groups

Books covering this topic
Yes. We have over 700 books in our library. Books covering Python are listed here and when you've selected a relevant book we'll link you on to Amazon to order.

Other Examples
This example comes from our "Python and SQL databases" training module. You'll find a description of the topic and some other closely related examples on the "Python and SQL databases" module index page.

Full description of the source code
You can learn more about this example on the training courses listed on this page, on which you'll be given a full set of training notes.

Many other training modules are available for download (for limited use) from our download centre under an Open Training Notes License.

Other resources
• Our Solutions centre provides a number of longer technical articles.
• Our Opentalk forum archive provides a question and answer centre.
The Horse's mouth provides a daily tip or thought.
• Further resources are available via the resources centre.
• All of these resources can be searched through through our search engine
• And there's a global index here.

Purpose of this website
This is a sample program, class demonstration or answer from a training course. It's main purpose is to provide an after-course service to customers who have attended our public private or on site courses, but the examples are made generally available under conditions described below.

Web site author
This web site is written and maintained by Well House Consultants.

Conditions of use
Past attendees on our training courses are welcome to use individual examples in the course of their programming, but must check the examples they use to ensure that they are suitable for their job. Remember that some of our examples show you how not to do things - check in your notes. Well House Consultants take no responsibility for the suitability of these example programs to customer's needs.

This program is copyright Well House Consultants Ltd. You are forbidden from using it for running your own training courses without our prior written permission. See our page on courseware provision for more details.

Any of our images within this code may NOT be reused on a public URL without our prior permission. For Bona Fide personal use, we will often grant you permission provided that you provide a link back. Commercial use on a website will incur a license fee for each image used - details on request.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2022: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/resources/ex.php • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb