Pyodbc - loading data inside a table causing error

I am trying to load the data inside the table trial and it says Invalid Column name - Name.

I am passing values inside Name and Area dynamically.

cursor.execute("insert into trial (NameofTheProperty, AreaofTheProperty) 
              values (Name, Area)")
cnxn.commit() 

Upvotes: 1

Views: 133

Answers (1)

alecxe
alecxe

Reputation: 473763

You need to have quotes around the column values so that they are not gonna be interpreted as column names instead:

insert into 
    trial (NameofTheProperty, AreaofTheProperty) 
values 
    ("Name", "Area")

Now, since you mentioned that you dynamically insert these values into the query, you can just let your database driver handle the quotes and other things like type conversions:

property_name = "Name"
property_area = "Area"

cursor.execute("""
    insert into 
        trial (NameofTheProperty, AreaofTheProperty) 
    values 
        (?, ?)""", (property_name, property_area))
cnxn.commit()

This is called query parameterization and is considered the safest and the most robust way to insert values into the SQL queries. These ? values are called "placeholders".

Note that the database driver is gonna put quotes around the string values automatically - no need to do it manually.

Upvotes: 1

Related Questions