Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot insert data into an sqlite3 database using Python

Tags:

python

sqlite

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 '\
      ')')
like image 354
Peter Horne Avatar asked Nov 29 '22 05:11

Peter Horne


2 Answers

Try to add

db.commit()

after the inserting.

like image 118
balpha Avatar answered Dec 05 '22 02:12

balpha


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.

like image 41
rado Avatar answered Dec 05 '22 04:12

rado