1

I have a function to query DB and return a value like below

def find_dase(Plants):
    conn = sqlite3.connect("dexro.db")
    cursor = conn.cursor()
    cursor.execute(("SELECT Years FROM Plants_no WHERE Plant=?"),(Plants,))
    data = cursor.fetchall()
    conn.close()
    return data

when i execute this i am getting a list instead of the value

print(find_dase('dex'))
print(type(find_dase('dex')))

Output:

[('10',)]      
<class 'list'>

How can i fetch only the integer value

5
  • Can you use .fetchone() instead .fetchall()? Commented Jul 9, 2018 at 8:16
  • it gives <class 'tuple'> Commented Jul 9, 2018 at 8:17
  • 2
    Yes, it returns a row, in this case the row contains only one value, Years. So .fetchone()[0] Commented Jul 9, 2018 at 8:19
  • Thanks, this works Commented Jul 9, 2018 at 8:21
  • No problem, I wrote answer then :) Commented Jul 9, 2018 at 8:26

1 Answer 1

2

cursor.fetchall() fetches all rows in form of list. In this case the row has only one value Year, so list of one valued tuples.

Solution:

Use .fetchone() to fetch only one row in form of tuple and index it:

def find_dase(Plants):
    conn = sqlite3.connect("dexro.db")
    cursor = conn.cursor()
    cursor.execute(("SELECT Years FROM Plants_no WHERE Plant=?"),(Plants,))
    data = cursor.fetchone()[0]  # THIS IS CHANGED
    conn.close()
    return data
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.