I have a small method to get one column from a MySQL database. It works, but it is returning a tuple like:
((1L,),(2L,),(3L,), ...)
I would like to get just a list [1L, 2L, 3L,...] (or even casting to int instead of long). I know I could write a loop to do it manually, but probably there is a fancier, more pythonish way of doing it.
This is the code of my function, just in case there is some way to get the MySQL result directly into a list and I haven’t heard of it!
def getFTPSentNotamIds():
selectedIds = None
try:
# Connect to database
db = MySQLdb.connect(host=Constants.database_host,
user=Constants.database_user,
passwd=Constants.database_passwd,
db=Constants.database_name)
# Create a cursor to execute queries
cursor = db.cursor()
# Get every ObjectID of those objects which are Selected=1
cursor.execute('SELECT ObjectID FROM MYTABLE WHERE Selected=1')
# Get the NOTAMS
selectedIds = cursor.fetchall()
except MySQLdb.Error, e:
print 'ERROR ' + str(e.args[0]) + ': ' + str(e.args[1])
return selectedIds
each tuple in the returned value represent one row, if there is only 1 element in the row,
you can use list comprehension like following to get your list containing ObjectID’s as:
In your function you can do
return [x[0] for x in selectedIds]