[英]Postgresql add values to a column with a for loop (on Python)
I've added a new column to my postgresql table. 我在我的postgresql表中添加了一个新列。 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
吗?
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. 您需要在循环的主体中执行
UPDATE
语句。 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. 假设Table_name的第一行是主索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.