flask 怎么调用 sqlite

2015-10-30 20:49:12 +08:00
 honmaple
需要将 db 里的数据输出到网页,不知道为什么一直不对
下面是部分源码
```
books = get_db()
cur = books.execute('select * from BOOKS')
id = []
for row in cur:
id.append(row[0])
ID = id
return render_template("index.html",ID=ID)
```
### 函数
```
DATABASE = 'books.db'
def init_db():
with closing(connect_db()) as db:
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()

def connect_db():
return sqlite3.connect(DATABASE)
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = connect_db()
return db
```
### 模板
```
{% for i in ID %}
<div>{{i}}</div>
{% endfor %}
```
**确定 books.db 里有数据,但结果什么都不显示**
2732 次点击
所在节点    Python
4 条回复
SErHo
2015-10-30 21:11:01 +08:00
DATABASE 用绝对路径试试?
honmaple
2015-10-30 21:25:41 +08:00
@SErHo 试过了,出现 can't open database 还是什么的又换回来了
ericls
2015-10-31 04:29:22 +08:00
flask 调用 sqlite 的方式和 python  调用 sqlite 的方式一样

你可以先不用渲染模板 直接在 shell 里面试一试
honmaple
2015-10-31 11:17:40 +08:00
@ericls @SErHo 多谢回答,已经解决了,使用
g.db = sqlite3.connect(database)
cur = g.db.execute('SELECT * from BOOKS')
Recipes = [dict(ID=row[0],
TYPE=row[1],
CONTENT=row[2]) for row in cur.fetchall()]
g.db.close()
return render_template("index.html",ID=ID)
database 使用绝对路径
就这几句就行,没用什么函数,也不知道官方文档为什么讲的那么复杂,还不明不白

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/232365

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX