简体   繁体   中英

Postgresql add values to a column with a for loop (on Python)

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

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM