3

I have a Python list newcol that I want to add to an existing Postgresql table. I have used the following code:

conn = psycopg2.connect(host='***', database='***', user='***', password='***')
cur = conn.cursor()
cur.execute('ALTER TABLE %s ADD COLUMN %s text' % ('mytable', 'newcol'))
conn.commit()

This added the list newcol to my table, however the new column has no values in it. In python, when I print the the list in python, it is a populated list.

Also, the number of rows in the table and in the list I want to add are the same. I'm a little confused.

Thanks in advance for the help.

3
  • 2
    ALTER TABLE ... ADD COLUMN ... doesn't add values from list - it only add/create (empty) column. To add values to this column you need UPDATE - learn SQL. Commented Oct 3, 2016 at 5:31
  • @furas, woops, got a little confused when pulling it into Python. In SQL, I've manually added each line in the past. Is there a way to update the values and add the whole list? Commented Oct 3, 2016 at 5:52
  • You could use for loop to get element from list and execute UPDATE query. Commented Oct 3, 2016 at 6:01

1 Answer 1

2

ALTER TABLE only changes table schema -- in your case it will create the new column and initialize it with empty (NULL) values.

To add list of values to this column you can do: UPDATE TABLE <table> SET ... in a loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.