Flask Select 查询返回游标对象或空列表而不是值元组

问题描述 投票:0回答:1

这是我的代码

app.py

from flask import Flask, render_template, request, g

import sys
import sqlite3
import os

current_directory = os.path.dirname(os.path.abspath(__file__))

app = Flask(__name__)

@app.route('/student')
def student():
    connection = sqlite3.connect(current_directory + "/sss.db")
    cursor = connection.cursor()
    Lastname='Volley'
    Firstname='Vlad'
    result = cursor.execute("SELECT * FROM Students WHERE Firstname=? AND Lastname=?", (Firstname,Lastname))
    result.fetchone()
    res = list(result)
    connection.commit()
    connection.close()
    return render_template('student.html', res=res)

if __name__ == "__main__":
    app.debug=True
    app.run(port=3000)

另外 - 在学生 html 文件中 - 我正在尝试显示数据以确保其存在。
正如您从应用程序文件中看到的,我正在将查询结果转换为列表。这样我就可以在学生 html 页面上可视化它,但它总是返回一个空列表。
数据在sqlite3数据库中。

下面的学生 HTML 代码片段:

 <div>
        <div class="container mr-t">
          <h1>Is this You?</h1>
          <div class="container">
              <p>{{res}}</p>
          </div>
          <form id="emailForm">
              <button type="submit">Find Email and Password</button>
              <button style="background-color: red;" type="submit">Clear</button>
          </form>
          <p id="result"></p>
        </div>
</div>

下面是我的数据库文件的图像: Here is a image of my database showing the data inside

python flask sqlite3-python
1个回答
1
投票

主要问题在这一行

result = cursor.execute("SELECT * FROM Students WHERE Firstname=? AND Lastname=?", (Firstname,Lastname))
,这就是为什么你得到一个光标对象。您不需要将
cursor.execute
分配给变量。我们只是在游标对象内部定义将执行哪个语句。

然后,在下一行中,

result.fetchone()
,您忘记了将结果存储在变量中。请参阅下面我的建议。

from flask import Flask, render_template, request, g

import sys
import sqlite3
import os

current_directory = os.path.dirname(os.path.abspath(__file__))

app = Flask(__name__)

@app.route('/student')
def student():
    connection = sqlite3.connect(current_directory + "/sss.db")
    cursor = connection.cursor()
    Lastname='Volley'
    Firstname='Vlad'
    # we don't need to assign this to a variable
    cursor.execute("SELECT * FROM Students WHERE Firstname=? AND Lastname=?", (Firstname,Lastname))
    # now we get the results using the cursor object, which will execute the select statement
    result = cursor.fetchone()
    res = list(result)
    connection.commit()
    connection.close()
    return render_template('student.html', res=res)

if __name__ == "__main__":
    app.debug=True
    app.run(port=3000)

© www.soinside.com 2019 - 2024. All rights reserved.