Home > front end >  Add data to Python list directly from database
Add data to Python list directly from database

Time:07-13

I have a Python list with locations in my script which I added manually. And I have a DB called Budget.db which already has 50 locations.

connection = sqlite3.connect('C:/Users/Administrator/project/BUDGET.db')

locationList = [
'Aberdeen; Aberdeen Airport',
'Belfast; Belfast International Airport Aldergrove',
'Belfast; George Best Belfast City Airport',
'Birmingham; Terminal Building',
'Blackpool; Blackpool Airport',
'Bristol; Bristol Airport',
'Cardiff; Meet And Greet Only',
'Edinburgh; Car Rental Centre',
'Exeter; Exeter Airport',
'Glasgow; Glasgow International Airport',
]

My question is, how can I add the 50 locations from my DB into my Python list ? Or it would be even better if the whole list is imported from the DB instead of me doing it manually. Thx appreciate the help

Database name : Budget.db
Table name : Locations
Column name : Name (TEXT)

CodePudding user response:

just query and collect

import sqlite3

connection = sqlite3.connect('C:/Users/Administrator/project/BUDGET.db')
cursor = connection.cursor()

try:
    results = [
        row[0]
        for row in cursor.execute("SELECT Name FROM Locations").fetchall()
    ]
finally:
    cursor.close()
    connection.close()
  • Related