Skip to content

Instantly share code, notes, and snippets.

@Weizhang2017
Created October 30, 2019 02:03
Show Gist options
  • Save Weizhang2017/4f87b914acd4b93270f817ca5d29b852 to your computer and use it in GitHub Desktop.
Save Weizhang2017/4f87b914acd4b93270f817ca5d29b852 to your computer and use it in GitHub Desktop.
Python interacting with database
#At low level, interacting with a database from SQL statements is straightforward
stocks = [
('GOOG', 100, 490.1),
('AAPL', 50, 545.75),
('FB', 150, 7.45),
('HPQ', 75, 33.2)
]
import sqlite3
db = sqlite3.connect('database.db')
c = db.cursor()
c.execute('create table portfolio (symbol text, shares integer, price real)')
db.commit()
c.executemany('insert into portfolio values (?,?,?)', stocks)
db.commit()
for row in db.execute('select * from portfolio'):
print(row)
min_price = 100
for row in db.execute('select * from portfolio where price >= ?', (min_price, )):
print(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment