2014-04-03 43 views
2

我很抱歉提出這樣一個基本問題,但我是SQlite3的新手,並且無法啓動。我正在試圖用一張表建立一個數據庫。我使用下面的代碼來建立一個表格。在sqlite3中創建一個表python

import sqlite3 
conn = sqlite3.connect('example.db') 
c = conn.cursor() 
c.execute('''CREATE TABLE mytable 
     (start, end, score)''') 

但每當我嘗試更新或訪問表似乎它不存在或可能存在於不同的數據庫中。我也嘗試創建一個名爲example.mytable的表,但我得到了以下錯誤: sqlite3.OperationalError:未知數據庫示例

我在想什麼? 謝謝

+1

程序這段代碼是退出的一部分嗎?你什麼時候嘗試訪問表格? –

+0

適合我。顯示試圖更新或訪問表的代碼。 –

+0

我使用了這種方法並進行了檢查,表格確實存在。我在conn.commit()之後關閉了連接。然後我重新打開它,數據在那裏並關閉它。第三次嘗試訪問它時,我收到一個表不存在的錯誤 - 是否必須每次都提交併關閉? – user2906979

回答

1

我認爲插入後需要一個提交(模式更改,如新表應該自動提交)。我建議將完整路徑添加到數據庫以確保您下次訪問同一位置。

這裏是你的代碼的擴展:

import sqlite3 

def create(): 
    try: 
     c.execute("""CREATE TABLE mytable 
       (start, end, score)""") 
    except: 
     pass 

def insert(): 
    c.execute("""INSERT INTO mytable (start, end, score) 
       values(1, 99, 123)""") 

def select(verbose=True): 
    sql = "SELECT * FROM mytable" 
    recs = c.execute(sql) 
    if verbose: 
     for row in recs: 
      print row 

db_path = r'C:\Users\Prosserc\Documents\Geocoding\test.db' 
conn = sqlite3.connect(db_path) 
c = conn.cursor() 
create() 
insert() 
conn.commit() #commit needed 
select() 
c.close() 

輸出:

(1, 99, 123) 

關閉程序,如果我登錄到SQLite數據庫中的數據仍然存在之後。