我是 SQLite 的初学者,所以如果我要问的问题看起来很愚蠢,请多多包涵。
我目前有一个名为“Status”的数据库,其中包含两列“stamp”和“messages”。 “messages”包含文本,“stamp”包含时间戳。
我想读取该数据库的最后 10 个条目,并将它们显示到 HTML 页面。
我用来从数据库读取的代码是:
@cherrypy.expose
def readStatus(self):
con = lite.connect('static/database/Status.db')
output = ""
with con:
cur = con.cursor()
cur.execute("SELECT messages FROM Status ORDER BY stamp DESC LIMIT 5")
print "The Status database now contains:"
for row in cur:
print row
output = output + row
return output
我用来将消息打印到 HTML 页面上的代码是
@cherrypy.expose
def homepage(self):
"""Display the home page showing status update
"""
page = get_file(staticfolder+"/html/homePage.html")
page = page.replace("$STATUS", self.readStatus())
return page
但是,我收到此错误消息:
File "proj1base.py", line 133, in homepage
page = page.replace("$STATUS", self.readStatus())
File "proj1base.py", line 305, in readStatus
output = output + row
TypeError: cannot concatenate 'str' and 'tuple' objects
我不完全确定这是什么意思,我假设它是说“输出”和“行”之间的类型不匹配。但是,'row'应该读取的是数据库'status'的'messages'列,它是一个字符串,'output'也是一个字符串。所以我不知道发生了什么,想知道是否有人可以提供帮助?
最佳答案
当您仅查询一列时,SQLite 也支持查询多列。但是,为了保持一致性,Python 总是 将它们放在一个元组中。您可能想要获取元组的第一个元素,将是一个字符串:
output = output + row[0]
关于python - 使用 Python、SQLite 和 HTML,我如何从数据库读取数据并打印到页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9952655/