对Sqlite数据库的基本查询 - 需要SQLAlchemy吗?

时间:2017-02-01 19:42:44

标签: sqlite flask sqlalchemy

我做了一些计算,并将结果存储在sqlite数据库中的多个表中。现在我希望将这些结果显示在网站上,然后将自己介绍给烧瓶。 我已经做了一些第一步,并且还连接到了一个sqlite数据库 - 并对表((SELECT * FROM <table>))进行了简单的“打印”以获得第一印象。

我想要实现的目标不仅仅是对一个表的简单查询/打印。会有我想要的页面 - 例如3(html)表。这三个(html)表来自一个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是什么意思?

谢谢。

1 个答案:

答案 0 :(得分:0)

很明显你没有尝试过那么多烧瓶,但我会给你一个快速的介绍:

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 %}