2

So I have a table that is being updated with new columns every time a new instance of a class is being instantiated. Here's my code doing that.

query = "alter table test add column %s integer"
rows = (str(Driver.count), str(Driver.count+1))
for c in rows:
    cur.execute(query, (AsIs(c),))
conn.commit()

Driver.count is the counter that is being incremented every new instance of the class. Now when I want to update the table, I use a command similar to this:

cur.execute("INSERT INTO test (str(Driver.count), str(Driver.count+1)) \
VALUES (%d, %d)" % (currentRow,currentCol));

Where the two columns I am specifying are variables. I know the above command won't work, since the column variables somehow need to be outside of the quotations, like when I specify the values to be inserted. How can I do this?

2
  • Your column names will be numbers, is that correct? Commented Aug 16, 2016 at 22:44
  • John's answer will work for you, but you should know that it is a bad idea to use numbers as column names. If possible, you should prepend some text to number, like dc1, dc2, ... Commented Aug 17, 2016 at 15:31

1 Answer 1

2
cur.execute('INSERT INTO test ("%d", "%d") VALUES (%d, %d)'
    % (Driver.count, Driver.count+1, currentRow, currentCol))

Or using newer syntax:

cur.execute('INSERT INTO test ("{}", "{}") VALUES ({}, {})'.format(
    Driver.count, Driver.count+1, currentRow, currentCol))
Sign up to request clarification or add additional context in comments.

2 Comments

If those column names are numbers, this may still error out (in PostgreSQL). You will need to make sure the column names have double quotes around them. So something like: ... 'INSERT INTO test ("{}", "{}") VALUES ({}, {})'.format(...
That is still not correct. You have to use double-quotes, not single-quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.