4

I'm tring to use this code to read all temperature values from a sqlite database column, but the output is showing [(u'29',), (u'29',), (u'29',)] and I'm only storing the numeric value in the database. I would like the output to be [29, 29, 29]

import sqlite3

conn = sqlite3.connect("growll.db")
cursor = conn.cursor()

print "\nHere's a listing of all the records in the table:\n"
cursor.execute("select lchar from GrowLLDados")

print cursor.fetchall() 
1
  • If that is the output then - sure that only numbers are being stored? (As opposed to numeric strings.) SQLite will do some basic type-affinity conversions depending upon column type, but otherwise, what you get is what is in the database. Commented Dec 27, 2012 at 1:14

2 Answers 2

6

Try this:

import sqlite3

conn = sqlite3.connect("growll.db")
cursor = conn.cursor()

print "\nHere's a listing of all the records in the table:\n"
cursor.execute("select lchar from GrowLLDados")    

print [int(record[0]) for record in cursor.fetchall()]
Sign up to request clarification or add additional context in comments.

5 Comments

Worked Perfectly! thanks Since I'm learning python would you know how I would do the same if I the data was a char like L instead of 29?
Sure: print [record[0] for record in cursor.fetchall()] should work if fetchall() returns [(u'L',), (u'L',), (u'L',)] for example. The u in front of the strings just mean that they are unicode strings, by the way.
To use this data how I can store it in a new variable because if I trie to read the record varialble there is only the last read variable not the list. Thanks
To get [29, 29, 29] into a variable, assign it to one instead of printing it, i.e. records = [int(record[0]) for record in cursor.fetchall()]. Is that what you mean?
Yes thats it I'll use matplot with this data.
1

print [int(i[0]) for i in cursor.fetchall()]

Let me know how you get on.

2 Comments

Won't this throw a TypeError? int() needs a string, not a tuple
yes I have: TypeError: int() argument must be a string or a number, not 'tuple'

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.