0

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.

Akavall
  • 82,592
  • 51
  • 207
  • 251
  • I tried running your code and it works fine for me. Please post the exact code you tried using `>` and the output you got when you ran it. – Duncan Feb 06 '12 at 15:49
  • 1
    Surely this is an SQL question, not a Python one? – Daniel Roseman Feb 06 '12 at 15:50
  • Duncan, I got that line to work with: price = 50 t = (price,) c.execute('select * from stocks where price>?', t) z4 = c.fetchall() print z4 Thanks – Akavall Feb 06 '12 at 16:23

1 Answers1

3
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?

Mike Graham
  • 73,987
  • 14
  • 101
  • 130
eumiro
  • 207,213
  • 34
  • 299
  • 261