Thom G Thom G - 7 months ago 14
Python Question

Is there a way to use a column header in a database as a variable in Python?

I'll preface this saying I'm pretty new to python.

I have a database and need to access it using Python and SQLite. That's the easy part. I have created the table and column names etc, such as:

c.execute("CREATE TABLE Tanks \
(ID INT PRIMARY KEY NOT NULL,\
...
DIR_Radius INT NOT NULL,\
DIR_Dish1 INT NOT NULL,\
DIR_Dish2 INT NOT NULL,\
DIR_Length INT NOT NULL,\


And so on. So what I want to do is use the column header as a variable, i.e.

Dish1 = 'DIR_Dish1'


But as you may know in python that just assigns the string value to the variable name.

Saying

Dir_Dish1 > 0.001


Doesn't work either

def Dish_Vol():
if (Dish > 0.0001):
int1 = math.pi * Dish,
...


I am trying to check that the value in the comlumn DIR_Dish1 has a integer value greater than 0.001, so that I can go ahead and perform some calculation. How do I go about using a variable as such?

Answer

You would have run a SQL read on your table and iterate through the table:

for row in c.execute("SELECT DIR_Radius from Tanks"):
    if row[0]>0.0001:
        int1 = math.pi * row[0]
        ...

If you are trying to do some operations in the table and then modify an existing column or create a new column based on the operations you apply, you're better off using pandas. Pandas will allow you to create a data frame object from the query, do some processing (e.g. creating new columns or modifying existing columns), and then write the data frame object back into the SQL environment using to_sql().