Python 如何使用Flask显示SQL内部连接HTML

Python 如何使用Flask显示SQL内部连接HTML,python,html,sql,flask,Python,Html,Sql,Flask,我在显示另一个表中的值时遇到了一些问题(使用下面的代码更容易理解): contact.py def index(): db = get_db() contacts = db.execute( 'SELECT *' ' FROM contact INNER JOIN branche ON contact.branche_id = branche.branche_id' ' ORDER BY contact.nom ASC' )

我在显示另一个表中的值时遇到了一些问题(使用下面的代码更容易理解):

contact.py

def index():
    db = get_db()
    contacts = db.execute(
        'SELECT *'
        ' FROM contact INNER JOIN branche ON contact.branche_id = branche.branche_id'
        ' ORDER BY contact.nom ASC'
    ).fetchall()
    return render_template('contact/index.html', contacts=contacts)
def index():
    db = get_db()
    contacts = db.execute(
        'SELECT contact.nom, contact.prenom, contact.adressemail, contact.codepostal, contact.ville, contact.telportable, branche.branche_nom'
        ' FROM contact INNER JOIN branche ON contact.branche_id = branche.branche_id'
        ' ORDER BY contact.nom ASC'
    ).fetchall()
    branches = db.execute(
        'SELECT branche_nom'
        ' FROM branche INNER JOIN contact ON contact.branche_id = branche.branche_id'
    ).fetchall()
    return render_template('blog/index.html', contacts=contacts, branches=branches)
import sqlite3  
import click
from flask import current_app, g
from flask.cli import with_appcontext

def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)

def init_db():
    db = get_db()

    with current_app.open_resource('schema.sql') as d:
        db.executescript(d.read().decode('utf8'))

@click.command('init-db')
@with_appcontext
def init_db_command():
    """Clear the existing data and create new tables."""
    init_db()
    click.echo('Initialized the database.')


def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = sqlite3.Row

    return g.db

def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()  
模板/contact/index.html

<table class="table table-hover">
      <thead class="thead-light">
          <th>Nom</th>
          <th>Prénom</th>
          <th>Adresse Mail</th>
          <th>Code Postal</th>
          <th>Ville</th>
          <th>Téléphone Portable</th>
          <th>Branche</th>
      </thead>
      <tbody>
      <div class="col-md-4">
        <div class="form-group">
      <div runat="server" id="div_columns" >
        {% for contact in contacts %}
         <tr>
             <td>{{ contact['nom'] }}</td>
             <td>{{ contact['prenom'] }}</td>
             <td>{{ contact['telportable'] }}</td>
             <td>{{ contact['adressemail'] }}</td>
             <td>{{ contact['codepostal'] }}</td>
             <td>{{ contact['ville'] }}</td>
             <td>{{ contact['telportable'] }}</td>
             <td>{{ branche['branche_nom'] }}</td>
             <td> 
                <a class="btn"><i class="fas fa-pencil-alt"></i></a>
                <a class="btn text-danger "><i class="fa fa-trash fa-lg"></i></a>
            </td>
          </tr>
          {% endfor %}
              <hr>
          </div>
          </div>
          </div>
      </tbody>
    </table>
DROP TABLE IF EXISTS contact;
DROP TABLE IF EXISTS branche;

CREATE TABLE contact (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  nom TEXT NOT NULL,
  prenom TEXT NOT NULL,
  adressemail TEXT NOT NULL,
  adressepostale TEXT NOT NULL,
  codepostal INTEGER NOT NULL,
  ville TEXT NOT NULL,
  telfixe INTEGER NOT NULL,
  telportable INTEGER NOT NULL,
  branche_id INTEGER NOT NULL,
  FOREIGN KEY (branche_id) REFERENCES branche (branche_id)
);

CREATE TABLE branche (
  branche_id INTEGER PRIMARY KEY AUTOINCREMENT,
  branche_nom TEXT UNIQUE NOT NULL
);
我要做的就是打印联系人信息(姓名、电话号码等),有一个信息不在
contact
表中,它是
branche
表中的
branche\u nom
,那么我的错误在哪里呢?我在终端计算机或浏览器终端内部没有任何错误

注意:当我禁用branche_nom的显示时,DB中存储的所有行都被打印出来,我没有任何东西,我想使用另一个表

编辑1:加载分支表格

contact.py

def index():
    db = get_db()
    contacts = db.execute(
        'SELECT *'
        ' FROM contact INNER JOIN branche ON contact.branche_id = branche.branche_id'
        ' ORDER BY contact.nom ASC'
    ).fetchall()
    return render_template('contact/index.html', contacts=contacts)
def index():
    db = get_db()
    contacts = db.execute(
        'SELECT contact.nom, contact.prenom, contact.adressemail, contact.codepostal, contact.ville, contact.telportable, branche.branche_nom'
        ' FROM contact INNER JOIN branche ON contact.branche_id = branche.branche_id'
        ' ORDER BY contact.nom ASC'
    ).fetchall()
    branches = db.execute(
        'SELECT branche_nom'
        ' FROM branche INNER JOIN contact ON contact.branche_id = branche.branche_id'
    ).fetchall()
    return render_template('blog/index.html', contacts=contacts, branches=branches)
import sqlite3  
import click
from flask import current_app, g
from flask.cli import with_appcontext

def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)

def init_db():
    db = get_db()

    with current_app.open_resource('schema.sql') as d:
        db.executescript(d.read().decode('utf8'))

@click.command('init-db')
@with_appcontext
def init_db_command():
    """Clear the existing data and create new tables."""
    init_db()
    click.echo('Initialized the database.')


def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = sqlite3.Row

    return g.db

def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()  
分支列表的屏幕截图

编辑2:db.py

def index():
    db = get_db()
    contacts = db.execute(
        'SELECT *'
        ' FROM contact INNER JOIN branche ON contact.branche_id = branche.branche_id'
        ' ORDER BY contact.nom ASC'
    ).fetchall()
    return render_template('contact/index.html', contacts=contacts)
def index():
    db = get_db()
    contacts = db.execute(
        'SELECT contact.nom, contact.prenom, contact.adressemail, contact.codepostal, contact.ville, contact.telportable, branche.branche_nom'
        ' FROM contact INNER JOIN branche ON contact.branche_id = branche.branche_id'
        ' ORDER BY contact.nom ASC'
    ).fetchall()
    branches = db.execute(
        'SELECT branche_nom'
        ' FROM branche INNER JOIN contact ON contact.branche_id = branche.branche_id'
    ).fetchall()
    return render_template('blog/index.html', contacts=contacts, branches=branches)
import sqlite3  
import click
from flask import current_app, g
from flask.cli import with_appcontext

def init_app(app):
    app.teardown_appcontext(close_db)
    app.cli.add_command(init_db_command)

def init_db():
    db = get_db()

    with current_app.open_resource('schema.sql') as d:
        db.executescript(d.read().decode('utf8'))

@click.command('init-db')
@with_appcontext
def init_db_command():
    """Clear the existing data and create new tables."""
    init_db()
    click.echo('Initialized the database.')


def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(
            current_app.config['DATABASE'],
            detect_types=sqlite3.PARSE_DECLTYPES
        )
        g.db.row_factory = sqlite3.Row

    return g.db

def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()  

首先,检查branche表是否填充了相关的ID,因为当两个表上的ID都不存在时,内部联接将返回空游标

其次,我会尽量避免在select中使用*并选择“select contact.,branche.”或选择表的实际列

第三,在尝试使用sqlite编写代码之后,我发现您应该在html模板中更改您当前的迭代器联系人,而不是branche

e、 例:非
{{branche['branche_nom']}}
但是
{{联系['branche_nom']}

除了输入错误之外,还必须添加一个命令,该命令将在连接初始化之后立即按名称识别列:
db.row\u factory=sqlite3.row

我已经运行了您的完整示例,它很有效!! 完整代码:

%%writefile contact.py
from flask import Flask, escape, url_for
from flask import render_template
import sqlite3

app = Flask(__name__)

def get_db():
    db = sqlite3.connect(r"/home/david/sqlite/db/pythonsqlite.db")
    return db

@app.route('/')
def index():
    db = get_db()
    db.row_factory = sqlite3.Row
    contacts = db.execute(
        'SELECT contact.nom, contact.prenom, contact.adressemail, contact.codepostal, contact.ville, contact.telportable, branche.branche_nom'
        ' FROM contact INNER JOIN branche ON contact.branche_id = branche.branche_id'
        ' ORDER BY contact.nom ASC'
    ).fetchall()
    return render_template('index.html', contacts=contacts)
结果:

造成混乱的主要原因是Jinja如何解释游标及其变量(列),不同的db有不同的db-API,您的第一种方法幸运地“理解”了列的名称(但并非全部来自branche表),就好像您尝试在联系人上迭代一样,您将只能访问索引列(通过数字),通过添加sqlite3.Row特性,光标将允许您按名称访问列,这就是最终传递给模板的内容。
解释如下:

您根本没有向模板传递
branche
变量,也没有在查询中选择任何
branche
列。@AKX我试图添加它,但(当前)没有任何更改1。您正在使用哪个数据库,它可以帮助检查语法?直接对db运行查询成功了吗?2.您有不明确的列(branche_id),如果处理不正确,可能会引起头痛,如果可以的话,为了测试起见,我会在每个表中将其重命名为不同的,以避免歧义。我使用SQLite作为db,您提到了哪个查询?没有任何指向
branche
表的链接,一切都很正常,这时我想在其他
contact
信息旁边显示
branche
名称,我想我发现你输入错误,在模板中你应该用contact['branche\u nom'替换branche['branche\u nom'],由于您正在对已经有branche__n列的联系人进行itrating,但您对每一行都使用contact,而不是branche。感谢您的解释,我知道问题出在哪里,但我不知道如何解决;我已经添加了包含db加载的db.py文件,并且在html文件中,联系人中联系人的循环
根本不起作用,
联系人
是like=NULL,我的
db.execute
函数有什么问题?或者这是另一个函数的问题吗?最重要的代码是db.row_factory=sqlite3.row,因为它用您可以使用的列名称包装获取的游标。为了进行测试,请尝试读取游标并在列上进行迭代,如果没有这行代码,您将只能通过索引号进行访问,使用这段代码您可以通过名称进行访问。