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
2
  • What is the primary key or unique column? Commented Aug 14, 2017 at 12:34
  • What does func do? Commented Aug 14, 2017 at 12:36

2 Answers 2

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.

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

4 Comments

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
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 !
Did your read this thread? stackoverflow.com/questions/24130305/…
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
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).

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.