Skip to content

Instantly share code, notes, and snippets.

@quiye
Last active May 19, 2018 04:11
Show Gist options
  • Save quiye/b083d744ac3852ef78ef72a31407f35d to your computer and use it in GitHub Desktop.
Save quiye/b083d744ac3852ef78ef72a31407f35d to your computer and use it in GitHub Desktop.
sqliteのデモ
import sqlite3
import json
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real, json text, id integer primary key AUTOINCREMENT)''')
c.execute(
"INSERT INTO stocks(date, trans, symbol, qty, price, json) VALUES ('2006-01-05','BUY','RHAT',100,35.14,'{\"name\":\"太郎1\"}')")
purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00, '{"name":"太郎2"}'),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00, '{"name":"太郎3"}'),
('2006-04-06', 'SELL', 'IBM', 500, 53.00, '{"name":"太郎4"}'),
('2006-04-06', 'SELL', 'IBM', 500, 53.00, '{"name":"太郎4"}'),
('2006-04-06', 'SELL', 'IBM', 500, 53.00, '{"name":"太郎4"}'),
('2006-04-06', 'SELL', 'IBM', 500, 53.00, '{"name":"太郎4"}'),
]
c.executemany('INSERT INTO stocks(date, trans, symbol, qty, price, json) VALUES (?,?,?,?,?,?)', purchases)
conn.commit()
t = ('IBM',)
c.execute('SELECT id,date,trans,json FROM stocks WHERE symbol=? order by id desc', t)
a = c.fetchall()
conn.close()
b = [(z[0], json.loads(z[3]).get("name")) for z in a]
print(b)
@quiye
Copy link
Author

quiye commented May 18, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment