0

I've added a new column to my postgresql table. Now I want to add values to this new added column. The only commands I found allow adding values but not in chosen rows of the column. What I'm tryin to have is:

cursor.execute('SELECT Column_name FROM Table_name')
rows = cursor.fetchall()
cursor.execute('ALTER TABLE Table_name ADD NewColumn_name type')
for row in rows:
     #Here I want to have a commands that adds a value (result of a function: func(row)) to every row of the new column, one by one something like: 

     NewColumn_name[i] = func(row)
     i = i+1
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
Ben Jo
  • 71
  • 1
  • 15

2 Answers2

0

Are you looking for update?

update table_name
    set column_name = ?;

Fill in the ? with the value you want (using a parameter is much preferred to munging the query string).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You need to execute UPDATE statements in your loop's body. Instead of this:

 NewColumn_name[i] = func(row)

try something like this (documentation):

cursor.execute('UPDATE Table_name SET NewColumn_name = %s WHERE id = %s', (func(row),row[0]);

Assuming the Table_name's first row is a primary index.

Laposhasú Acsa
  • 1,550
  • 17
  • 18
  • It actually worked at the beginning ( I printed the new added values) bit while it was running it ends with an error : **SSL SYSCALL error: EOF detected with python and psycopg** – Ben Jo Aug 18 '17 at 09:41
  • I suppose it can't be due to memory problem because they're not more than 10000 new values to add with the UPDATE querry ! – Ben Jo Aug 18 '17 at 09:45
  • Did your read this thread? https://stackoverflow.com/questions/24130305/postgres-ssl-syscall-error-eof-detected-with-python-and-psycopg – Laposhasú Acsa Aug 18 '17 at 09:46
  • Yep I did .. and I think I still have to add free more space. Does adding values like this take more space than adding them directly from a csv file? Because I dropped the whole table that normally contains 5 rows and replaced it with one with only 2 rows ... and with the first I don't get any memory problems – Ben Jo Aug 18 '17 at 10:26