Skip to content

Instantly share code, notes, and snippets.

@meunomemauricio
Created November 2, 2016 15:34
Show Gist options
  • Save meunomemauricio/959f79d5ff284b4859a950fe3e4b5684 to your computer and use it in GitHub Desktop.
Save meunomemauricio/959f79d5ff284b4859a950fe3e4b5684 to your computer and use it in GitHub Desktop.
Demonstration on how to set an In Memory database using SQLite3
#! /usr/bin/python
import sys
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
# Create table
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
print 80 * '~'
print 'Count: '
c.execute('SELECT COUNT(*) FROM stocks')
print c.fetchone()[0]
# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# Save (commit) the changes
conn.commit()
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print 80 * '~'
print c.fetchone()
# Larger example that inserts many records at a time
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]
c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)
print 80 * '~'
for row in c.execute('SELECT * FROM stocks ORDER BY price'):
print row
print 80 * '~'
print 'Count: '
c.execute('SELECT COUNT(*) FROM stocks')
print c.fetchone()[0]
print 80 * '~'
c.execute('SELECT trans, qty FROM stocks GROUP BY trans')
print c.fetchall()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment