简体   繁体   English

如何使用Sqlite3用列表中的值更新整个列

[英]How to update entire column with values in list using Sqlite3

I have a dataset stored locally in an sqlite3 database. 我有一个本地存储在sqlite3数据库中的数据集。 I extracted a column, performed some operations and now want to replace ALL of the values in the database column. 我提取了一个列,执行了一些操作,现在想替换数据库列中的所有值。 How can I do this? 我怎样才能做到这一点?

The length of the column and the list are guaranteed to be the same length. 列和列表的长度保证为相同的长度。 I simply want to update the table with the new values. 我只想用新值更新表。 Is there an easy way to do this all at once? 有一种简单的方法可以一次完成所有操作吗?

Using python 2.7 使用python 2.7

Edited to add: 编辑添加:

myList is a pandas series backed by a numpy array of dtype 'object'. myList是由dtype'object'的numpy数组支持的熊猫系列。 The table column, myCol is text formatted. 表列myCol是文本格式的。

In [1]: curr.execute('UPDATE test SET myCol= ?', myList)

---------------------------------------------------------------------------
ProgrammingError                          Traceback (most recent call last)
f:\python\<ipython-input-52-ea41c426502a> in <module>()
----> 1 curr.execute('UPDATE test SET myCol = ?', myList)

ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 401125 supplied.

Use the .executemany() method instead: 请改用.executemany()方法

curr.executemany('UPDATE test SET myCol= ?', myList)

However, myList must be a sequence of tuples here. 但是, myList 必须是一个元组序列。 If it is not, a generator expression will do to create these tuples: 如果不是,生成器表达式将创建这些元组:

curr.executemany('UPDATE test SET myCol= ?', ((val,) for val in myList))

Demonstration (with insertions): 演示(带插入):

>>> import sqlite3
>>> conn=sqlite3.connect(':memory:')
>>> conn.execute('CREATE TABLE test (myCol)')
<sqlite3.Cursor object at 0x10542f1f0>
>>> conn.commit()
>>> myList = ('foo', 'bar', 'spam')
>>> conn.executemany('INSERT into test values (?)', ((val,) for val in myList))
<sqlite3.Cursor object at 0x10542f180>
>>> list(conn.execute('select * from test'))
[(u'foo',), (u'bar',), (u'spam',)]

Note that for an UPDATE statement, you have to have a WHERE statement to identify what row to update. 请注意,对于UPDATE语句,您必须具有WHERE语句以标识要更新的 An UPDATE without a WHERE filter will update all rows. 没有WHERE过滤器的UPDATE将更新所有行。

Make sure your data has a row identifier to go with it; 确保您的数据具有行标识符。 in this case it may be easier to use named parameters instead: 在这种情况下,改用命名参数可能会更容易:

my_data = ({id=1, value='foo'}, {id=2, value='bar'})
cursor.executemany('UPDATE test SET myCol=:value WHERE rowId=:id', my_data)

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

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