4

I can successfully use Python to create a database and run the execute() method to create 2 new tables and specify the column names. 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 '\
 ')')
asked Jul 29, 2009 at 16:36
2
  • 1
    It worked fine for me. Are you getting any errors? Commented Jul 29, 2009 at 16:44
  • Nope, everything seemed to run fine other than the fact that the records weren't being added to the table. Commented Jul 29, 2009 at 17:19

2 Answers 2

21

Try to add

db.commit()

after the inserting.

answered Jul 29, 2009 at 16:46
Sign up to request clarification or add additional context in comments.

Comments

4

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

Cursors aren't used to insert data, but usually to read data, or update data in place.

answered Jul 29, 2009 at 16:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.