简体   繁体   English

使用Python,sqlite3和列表更新SQL数据库中的列

[英]Update a column in SQL database using Python, sqlite3 and a list

I have looked at other questions similar to this but some are ambiguous with little explanation of the answer. 我已经看过其他与此类似的问题,但是有些模棱两可,对答案的解释很少。 What I have is a sql database with 6 tables containing n number of columns. 我所拥有的是一个带有6个包含n个列的表的sql数据库。 I want to update, not insert, a column in one of the tables with data from a python list. 我想用一个python列表中的数据更新而不是插入其中一个表中的列。 This is a list called gbufids and consists of integers, but each entry is not contained in Tuples ie [0,1,2,3] not [(1,), (2,), (3,)]. 这是一个称为gbufids的列表,由整数组成,但每个条目都不包含在元组中,即[0,1,2,3]而不是[(1,),(2,),(3,)]。 The table name I want to change is called Versions and the column is called ObjectID. 我要更改的表名称称为“版本”,而该列称为“ ObjectID”。 I tried various ways I found, but none did the job in the way it needed to be done. 我尝试了各种发现的方法,但是没有一种方法可以完成所需的工作。 I used the following, which I believe should convert each item in the list to a tuple before updating the column (ObjectID) in the table (Versions): cur.executemany('UPDATE Versions set ObjectID=?', ((val,) for val in gbufids)) 我使用了以下内容,我认为应该在更新表(版本)中的列(对象ID)之前将列表中的每个项目转换为元组: cur.executemany('UPDATE Versions set ObjectID =?',((val,) for val in gbufids))

This is followed by a commit and a close. 接下来是提交和关闭。 I have read that I need a WHERE clause if I am using UPDATE, but I was a bit confused about row. 我已经读到,如果我使用UPDATE,则需要WHERE子句,但是我对行有点困惑。 To me, a row is all cells in a row, but this is probably not what is meant. 对我来说,一行是一行中的所有单元格,但这可能不是什么意思。 If anyone can provide an answer that is specific to my db, tables and column, it will be appreciated 如果有人可以提供特定于我的数据库,表和列的答案,将不胜感激

An UPDATE statement without a WHERE clause will cause all rows of the table to be updated with each value you pass into the executemany , meaning you'll end up with all rows populated with the last value you passed. 不带WHERE子句的UPDATE语句将使表的所有行都更新为您传递给executemany 每个值,这意味着您将最终所有行都填充有您传递的最后一个值。 In order to match each value with a particular row, you'll need some way to tell the database which row you want to replace in each run of the statement. 为了使每个值与特定行匹配,您需要某种方式来告诉数据库要在语句的每次运行中替换哪一行。 If you're sure the length of your list of updated values is equal to the number of rows in the table, and the order of your list is the same as the order of the rows you'd get with a simple SELECT * FROM table , then the easiest way would be to get the list of rowid s in the table: 如果您确定更新值列表的长度等于表中的行数,并且列表的顺序与使用简单的SELECT * FROM table获得的行的顺序相同,那么最简单的方法是获取表中的rowid列表:

rowids = [row[0] for row in cur.execute('SELECT rowid FROM Versions')]

Then you can pair up rowids and gbufids and pass that to your executemany : 然后,您可以将rowidsgbufids并将其传递给executemany

cur.executemany('UPDATE Versions SET ObjectID=? WHERE rowid=?', zip(gbufids, rowids))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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