【问题标题】:Basic queries to a Sqlite database - SQLAlchemy required?对 Sqlite 数据库的基本查询 - 需要 SQLAlchemy?
【发布时间】:2017-06-18 16:53:34
【问题描述】:

我做了一些计算并将结果存储在一个 sqlite 数据库中的许多表中。现在我想将这些结果显示在网站上,因此向烧瓶介绍了自己。 我已经迈出了第一步,还连接到了一个 sqlite 数据库 - 并简单地“打印”了一张表 ((SELECT * FROM <table>)) 以获得第一印象。

我想要实现的不仅仅是一个表的简单查询/打印。会有我想要的页面——比如 3 个(html)表。这三个 (html) 表来自一个 sqlite 表。

sqlite 表:

product | category | sales 2014 | sales 2015 | sales 2016 
------- | -------- | ---------- | ---------- | ---------- 
p1      | c1       | 23         | 21         | 25
p4      | c4       | 32         | 54         | 123
p3      | c6       | 42         | 34         | 54
...     | ...      | ...        | ...        | ...

表格将按(例如)“类别”过滤:

html-table 1

product | category | sales 2014 | sales 2015 | sales 2016 
------- | -------- | ---------- | ---------- | ---------- 
p1      | c1       | 23         | 21         | 25
...     | ...      | ...        | ...        | ...

html-table 2

product | category | sales 2014 | sales 2015 | sales 2016 
------- | -------- | ---------- | ---------- | ---------- 
p4      | c4       | 32         | 54         | 123
...     | ...      | ...        | ...        | ...

html-table 3

product | category | sales 2014 | sales 2015 | sales 2016 
------- | -------- | ---------- | ---------- | ---------- 
p3      | c6       | 42         | 34         | 54
...     | ...      | ...        | ...        | ...

将有一种方法可以通过许多 SELECT 语句来实现这一点。

问题是使用这些 RAW-SQL 语句是否是一种好习惯?

通常我会说不,因为这是我目前所读到的。你应该使用 SQLAlchemy。我试过了,但我很难理解它。此外,我认为这是“太多”(即我使用的表之间没有关系,我不会更新或更改网站上的表等)

我想从你那里知道的是,如果进一步研究 SQLAlchemy 是否对我想要实现的目标有用(即:查看网站上某些表的内容)?

谢谢。

【问题讨论】:

  • 如果你能看到自己曾经做过这样一个涉及 SQL 数据库的项目,那么我会说学习使用一点 SQLAlchemy 会很好。即使你不这样做,尝试一些对你来说新的东西并可能在你的简历中添加新技能也是一个很好的练习。但是,您不必这样做。只要您不接受可能进入您的查询或数据库的用户输入,那么这应该不是什么大问题。

标签: sqlite flask sqlalchemy


【解决方案1】:

很明显你没有尝试过太多烧瓶,但我会给你一个简单的介绍:

class Total(db.Model):
    product = db.Column(db.String())
    category = db.Column(db.String())
    ...

@app.route('/')
def index():
    total = Total.query.all() #get all records
    render_template('index.html', total=total)
#index.html
{% for record in total %}
    <table>
        <thead>
            <tr>
              <th>product</th>
              <th>category</th>
             </tr>
          </thead>
        <tr>
            <td>{{record.product}}</td>
            <td>{{record.category}}</td>
         </tr>
    </table>
{% endfor %}

【讨论】:

    猜你喜欢
    • 2011-09-13
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多