2009-07-29 196 views
4

我可以成功地使用Python創建數據庫並運行execute()方法來創建2個新表並指定列名。但是,我無法將數據插入數據庫。這是我想使用的數據插入到數據庫的代碼:無法使用Python將數據插入到sqlite3數據庫中

#! /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

它爲我工作得很好。你有什麼錯誤嗎? – 2009-07-29 16:44:23

+0

沒有,除了記錄沒有被添加到表格這一事實之外,一切似乎都運行良好。 – 2009-07-29 17:19:05

回答

19

嘗試插入後添加

db.commit() 

3

插入數據你不需要光標

只使用DB

db.execute()而不是c.execute()和擺脫C = db.cursor()線

遊標不用於插入數據,但通常用於讀取數據或更新數據。

+0

感謝您的建議,但我已經試過了。 – 2009-07-29 16:52:17

相關問題