Postgresql 使用 for 循环将值添加到列(在 Python 上)
Postgresql add values to a column with a for loop (on Python)
我在我的 postgresql table 中添加了一个新列。
现在我想向这个新添加的列添加值。
我发现的唯一命令允许添加值,但不允许在列的选定行中添加值。
我想要的是:
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
您在寻找 update
吗?
update table_name
set column_name = ?;
在 ?
中填写您想要的值(使用参数比修改查询字符串更可取)。
您需要在循环体中执行 UPDATE
语句。而不是这个:
NewColumn_name[i] = func(row)
尝试这样的事情 (documentation):
cursor.execute('UPDATE Table_name SET NewColumn_name = %s WHERE id = %s', (func(row),row[0]);
假设 Table_name 的第一行是主索引。
我在我的 postgresql table 中添加了一个新列。 现在我想向这个新添加的列添加值。 我发现的唯一命令允许添加值,但不允许在列的选定行中添加值。 我想要的是:
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
您在寻找 update
吗?
update table_name
set column_name = ?;
在 ?
中填写您想要的值(使用参数比修改查询字符串更可取)。
您需要在循环体中执行 UPDATE
语句。而不是这个:
NewColumn_name[i] = func(row)
尝试这样的事情 (documentation):
cursor.execute('UPDATE Table_name SET NewColumn_name = %s WHERE id = %s', (func(row),row[0]);
假设 Table_name 的第一行是主索引。