使用Python无法向sqlite3数据库插入数据

4

我可以成功使用Python创建数据库并运行execute()方法来创建2个新表并指定列名。然而,我无法向数据库插入数据。这是我尝试使用的代码:

#! /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 '\
      ')')

1
它对我来说运行得很好。你有收到任何错误吗? - Evan Fosmark
除了记录未被添加到表中之外,一切似乎都运行正常。 - Peter Horne
2个回答

21

尝试添加

db.commit()
在插入之后。

4

插入数据时不需要使用游标

只需使用 db.execute() 而不是 c.execute(),并且删除 c = db.cursor() 这一行

游标不用于插入数据,而通常用于读取数据或在原地更新数据。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接