Skip to content

Instantly share code, notes, and snippets.

@white-gecko
Last active November 7, 2019 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save white-gecko/ec8a6d7819bc8c1b63f664165ecc7e8e to your computer and use it in GitHub Desktop.
Save white-gecko/ec8a6d7819bc8c1b63f664165ecc7e8e to your computer and use it in GitHub Desktop.
sqlite python example
#!/usr/bin/env python3
# starting with https://docs.python.org/3.8/library/sqlite3.html
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute("DROP TABLE IF EXISTS stocks")
c.execute("DROP TABLE IF EXISTS stuff")
# Create table
c.execute('''CREATE TABLE if not exists stocks
(fnummer integer, name text, qty real)''')
c.execute('''CREATE TABLE if not exists stuff
(fnummer integer, name text, price real)''')
# Insert some data
stocks = [('2','hannes', 100),
('3','anna', 40),
('4','herbert', 20),
('6','holger', 22),
]
stuff = [('2','hans', 35.14),
('3','anne', 37.34),
('5','luise', 97.27),
('6','holger', 10.10),
]
c.executemany('INSERT INTO stocks VALUES (?,?,?)', stocks)
c.executemany('INSERT INTO stuff VALUES (?,?,?)', stuff)
# Save (commit) the changes
conn.commit()
# select the data with sqlite full outer join workaround
cursor = c.execute("""SELECT *
FROM stocks LEFT JOIN stuff ON stocks.fnummer = stuff.fnummer
UNION ALL
SELECT *
FROM stuff LEFT JOIN stocks ON stocks.fnummer = stuff.fnummer
WHERE stocks.fnummer IS NULL;""")
for row in cursor:
print(row)
print()
# … add some function to the projection
cursor = c.execute("""SELECT ifnull(stocks.fnummer, stuff.fnummer), ifnull(stocks.name, stuff.name), qty, price
FROM stocks LEFT JOIN stuff ON stocks.fnummer = stuff.fnummer
UNION ALL
SELECT ifnull(stocks.fnummer, stuff.fnummer), ifnull(stocks.name, stuff.name), qty, price
FROM stuff LEFT JOIN stocks ON stocks.fnummer = stuff.fnummer
WHERE stocks.fnummer IS NULL;""")
for row in cursor:
print(row)
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment