[英]Cannot insert data into an sqlite3 database using Python
I can successfully use Python to create a database and run the execute() method to create 2 new tables and specify the column names. 我可以成功使用Python创建数据库并运行execute()方法来创建2个新表并指定列名。 However, I cannot insert data into the database.
但是,我无法将数据插入数据库。 This is the code that I am trying to use to insert the data into the database:
这是我尝试用于将数据插入数据库的代码:
#! /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,))
Here is the code that I use to successfully create the database with: 以下是我用于成功创建数据库的代码:
#! /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 '\
')')
Try to add 尝试添加
db.commit()
after the inserting. 插入后。
To insert the data you don't need a cursor 要插入数据,您不需要光标
just use the db 只需使用数据库
db.execute() instead of c.execute() and get rid of the c = db.cursor() line db.execute()而不是c.execute()并删除c = db.cursor()行
Cursors aren't used to insert data, but usually to read data, or update data in place. 游标不用于插入数据,但通常用于读取数据或更新数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.