0
我是一名編程初學者,希望對學習SQLite和Python有一點幫助。使用Python和SQLite,我如何從數據庫中將項目讀入變量?
目前,我有一個名爲「Status.db」的數據庫,其中包含兩列。這些列是「印記」,類型INT和「消息」,連續輸入TEXT。
我使用來嘗試讀取的消息的一個實例的代碼,與特定的標記,ID,入變量「輸出」如下:
@cherrypy.expose
def comment(self, ID = None):
con = lite.connect('static/database/Status.db')
with con:
cur = con.cursor()
cur.execute("SELECT messages FROM Status WHERE stamp is ?", (ID,))
temp = cur.fetchone()
output = temp[0]
然而,當我執行該代碼,我得到一條錯誤信息:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/usr/lib/pymodules/python2.7/cherrypy/_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
File "proj1base.py", line 176, in comment
output = temp[0]
TypeError: 'NoneType' object is not subscriptable
我想知道如果任何人都可以澄清我這是什麼錯誤意味着,和我能做什麼,使其工作。
在此先感謝!
編輯: 下面是創建並寫入到數據庫
@cherrypy.expose
def writeStatus(self, newStatus=None, post=None):
"""Update the status file with the most recent status update
by inserting a timestamp and new status into a database
"""
con = lite.connect('static/database/Status.db')
stamp = time()
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Status(stamp INT, messages TEXT)")
cur.execute("INSERT INTO Status VALUES(?, ?)", (stamp, newStatus))
感謝指出了這一點對我來說,但即使是固定的,我仍然得到同樣的錯誤消息後。 – Synia 2012-03-31 06:24:36
@Synia,你的數據庫中是否有任何數據? (如果您確實有數據,您是否使用數據庫中的「ID」調用'comment'?) – huon 2012-03-31 07:06:34
@dbaupp嗨,感謝您的提醒。我檢查了我的數據庫,發現由於某種原因,分配給數據庫的戳有6個小數點,而我傳入的只有2個。我將它們全部更改爲整數,現在一切正常。 – Synia 2012-03-31 07:13:45