当我尝试检索已排序的行时,数据库返回空列表

时间:2019-10-30 19:20:11

标签: sqlite flask

我是烧瓶新手。我正在尝试根据表单中的所选选项对数据库中的行进行排序。问题是,我得到的是空列表,而不是其中包含行数据的元组列表。尽管发布请求和我的数据库都不都是空的,并且我的SQL请求正在sqlitebrowser中与我当前的数据库一起工作。

routes.py:

@bp.route('/poll-process', methods=['POST', 'GET'])
def process():
    form =  ChoiceForm(request.form)
    if request.method == 'POST':
        select = request.form.get('sel')  
        if select:
            print(select)
            db = get_db()
            res = db.execute(
            '''SELECT username, sex, city, emotion, month, poll_time
                FROM poll
                JOIN author
                    ON poll.author_id = author.id
                ORDER BY sex ASC''', (select)                  
            ).fetchall()
            print(res) 
            db.close
    return render_template('process.html', form=form)

shema.sql:

DROP TABLE IF EXISTS author;
DROP TABLE IF EXISTS poll;

CREATE TABLE `author` (
    `id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    `username`  TEXT NOT NULL,
    `sex`   TEXT NOT NULL
);

CREATE TABLE `poll` (
    `poll_id`   INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    `city`  TEXT NOT NULL,
    `emotion`   TEXT NOT NULL,
    `month` TEXT NOT NULL,
    `poll_time` TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `author_id`   INTEGER,   
  FOREIGN KEY(`author_id`) REFERENCES `author`
);

process.html:

<form method="post">
  <!-- select -->
  <div class="form-group mt-4">  
    <h2>Choose criteria to sort</h2>
    <select class="custom-select" name="sel">        
      {% for field in form.sel %}
        <option>{{ field }}</option>    
      {% endfor %}      
    </select>
    ...
    {{form.submit(class="btn btn-primary")}}
</form>

这是我的输出:

 * Serving Flask app "flaskapp" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 231-471-963
poll_time
[]
127.0.0.1 - - [30/Oct/2019 21:16:59] "POST /poll-process HTTP/1.1" 200 -

谢谢!

1 个答案:

答案 0 :(得分:1)

routes.py

中更改查询
@bp.route('/poll-process', methods=['POST', 'GET'])
def process():
    form =  ChoiceForm(request.form)
    if request.method == 'POST':
        select = request.form.get('sel')  
        if select:
            print(select)
            db = get_db()
            res = db.execute(
            '''SELECT username, sex, city, emotion, month, poll_time
                FROM poll
                JOIN author
                ON poll.author_id = author.id
                ORDER BY %s''' % (select,)                  
            ).fetchall()
            print(res) 
            db.close
    return render_template('process.html', form=form)