无法使用Python向sqlite3数据库插入数据
我可以顺利地用Python创建一个数据库,并且使用execute()方法创建两个新表,并指定列名。但是,我无法往数据库里插入数据。这是我尝试用来插入数据的代码:
#! /usr/bin/env python
import sqlite3
companies = ('GOOG', 'AAPL', 'MSFT')
db = sqlite3.connect('data.db')
c = db.cursor()
for company in companies:
c.execute('INSERT INTO companies VALUES (?)', (company,))
这是我用来成功创建数据库的代码:
#! /usr/bin/env python
import sqlite3
db = sqlite3.connect('data.db')
db.execute('CREATE TABLE companies ' \
'( '\
'company varchar(255) '\
')')
db.execute('CREATE TABLE data ' \
'( '\
'timestamp int, '\
'company int, '\
'shares_held_by_all_insider int, '\
'shares_held_by_institutional int, '\
'float_held_by_institutional int, '\
'num_institutions int '\
')')
2 个回答
4
要插入数据其实不需要使用游标。
只需要用数据库的操作。
用 db.execute() 代替 c.execute(),而且可以去掉 c = db.cursor() 这一行。
游标通常是用来读取数据或者直接更新数据的,而不是用来插入数据的。
21
试着在插入之后添加
db.commit()
。