Hanley Soilsmith Hanley Soilsmith - 11 months ago 80
Python Question

How to pass a python variable as a sqlite column name in a for-loop

It looks similar questions have been asked but I didn't find an answer.

The cities in the cities list have corresponding column names in a database. I'm trying to find a specific city's pressure with pyowm, then insert that value into the appropriate column.

The error is that there is not a column named "city". I can see what the problem is but do not know how to fix it. Any help is greatly appreciated!

import pyowm
import sqlite3

conn = sqlite3.connect(r"C:\Users\Hanley Smith\Desktop\machinelearning\pressure_table.db")
cursor = conn.cursor()

owm = pyowm.OWM('eb68e3b0c908251771e67882d7a8ddff')

cities = ["tokyo", "jakarta"]

for city in cities:
weather = owm.weather_at_place(city).get_weather()
pressure = weather.get_pressure()['press']
cursor.execute("INSERT INTO PRESSURE (city) values (?)", (pressure,))


Answer Source

concatenate the variable name with the string like this.

cursor.execute("INSERT INTO PRESSURE (" + city + ") values (?)", (pressure,))

or a much cleaner way with %s

cursor.execute("INSERT INTO PRESSURE (%s) values (?)" % (city), (pressure,))