Reputation: 86198
I was trying to figure out how to work with SQLite database using python, but seem to be stuck. I think I am missing something basic. I was following this tutorial: http://docs.python.org/library/sqlite3.html
I set up a database such that it contains the following information:
import sqlite3
conn = sqlite3.connect('SQL_test_3') #this creates a seperate file
c = conn.cursor()
c.execute('''create table stocks
(date text, trans text, symbol text,
qty real, price real)''')
data = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]
for t in data:
c.execute('insert into stocks values (?,?,?,?,?)', t)
conn.commit()
c.close()
My problems arise when I try to extract the data; the tutorial explains how to extract the data if one of the characteristics are satisfied, for example:
(When I open the database in another file)
import sqlite3
conn = sqlite3.connect('SQL_test_3')
c = conn.cursor()
price = 53
t = (price,)
c.execute('select * from stocks where price=?', t)
print c.fetchall()
The above works perfect, but what if I want extract information for all the assets who's price is greater that 50, I can't do it. Doing price > 50 and price>? doesn't work...
So my questions are:
1) How do I extract information for an asset when the key criteria is fits in a given range, for example price > 50 or 40 < price < 70.
2)And what if I wanted to have two criteria, for example information for IBM stocks, and if the stock was traded at, say, price greater than 50.
I feel that my questions are very beginner/basic, but I couldn't find the answers to them in the tutorial.
Any help is appreciated.
Thanks in Advance.
Upvotes: 0
Views: 7616
Reputation: 212895
c.execute('select * from stocks where price > ?', (50,))
c.execute('select * from stocks where price between ? and ?', (40, 70))
c.execute('select * from stocks where price > ? and symbol = ?', (50, 'IBM'))
Is this ok or do you need a universal solution?
Upvotes: 3