Python_newbie
Python_newbie

Reputation: 203

SQLite and Python - Fetch value from DB

I have a table in sqlite DB (alpha.db) named alphanum and it has the following columns and values in it.

enter image description here

I have a function in python to fetch values from this DB:

import sqlite3
def viewdata(number):
    conn = sqlite3.connect("alpha.db")
    cursor = conn.cursor()
    cursor.execute(("SELECT Alpha,beta,gamma, number FROM alphanum WHERE number=?"),(number,))
    data=cursor.fetchall()
    conn.close()
    return data


print(viewdata(2.6))

if I use this I am getting the following value:

45,54,87,2.6

Here, the number column holds the starting value, i.e., from Number 2.6 till 5.9 it belongs to Queue 1, from Number 6 till 8.4, it belongs to Queue 2 and so on.

Now, if I want to get the Alpha, Beta, Gamma values from this table for a number that lies between these Queue what query should I use? i.e., if I input the value of 5.8, I should get the alpha beta and gamma values of Queue 1 since from Number 2.6 till Number 5.9 it belongs to Queue 1.

I am not sure on how to use Declare variables in SQLite, any help would be appreciated.

Upvotes: 0

Views: 233

Answers (1)

zwer
zwer

Reputation: 25829

If the numbers are cumulative, as per your comment, all you need is to fetch the entries whose Number value is lower or equal to the passed number and pick only the highest one, e.g.:

cursor.execute("""SELECT Alpha, Beta, Gamma, Number FROM alphanum 
               WHERE Number<=? ORDER BY Number DESC LIMIT 1""", (number, ))

Upvotes: 1

Related Questions