繁体   English   中英

sqlalchemy.exc.OperationalError:(MySQLdb._exceptions.OperationalError)(1054,“'字段列表'中的未知列'detail.id'”)

[英]sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1054, "Unknown column 'detail.id' in 'field list'")

我建立了一个小型网站,任何人都可以在其中存储“姓名,email,电话”,但是当我从数据库中检索数据时,我收到了这个错误。 我不知道为什么?

我会花两天时间来解决这个错误,但我仍然坚持下去。

sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1054, "Unknown column 'detail.id' in 'field list'") [SQL: SELECT detail.id AS detail_id, detail.name AS detail_name, detail.email AS detail_email,detail.phone AS detail_phone,detail.date AS detail_date FROM detail](此错误的背景: http://sqlalche.me/e/e3q8

我的代码run.py

from flask import Flask, render_template, request, redirect, url_for, session
from db import db
import datetime

# Every website is application in 'flask'
app = Flask(__name__, template_folder='template')
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:''@localhost/flask' # 'test' is name of your database
# Database access through 'username'= root  and 'password'= None
# My username is 'root' cause I'm on the local host and I'd set any password
# One more thing password is after two dots :
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True



# database access
class detail(db.Model):
    def __init__(self, name, phone, email):
        self.name = name
        self.email = email
        self.phone = phone

    # table name as is it in your database
    __tablename__='detail'
    # give column names same as in your database otherwise it will give you error
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20), nullable=False)
    email = db.Column(db.String(20), nullable=False)
    phone = db.Column(db.String(13), nullable=False)
    date=db.Column(db.DateTime, default=datetime.datetime.strftime(datetime.datetime.now(), '%d-%m-%Y   %I:%M:%S'))



# routing( setting end points in website) with ['post', 'get'] method
@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method=='POST':
        name = request.form['name']
        email = request.form['email']
        phone = request.form['phone']

        try:
            # commit to add value in database
            data = detail(name=name, email=email, phone=phone)
            db.session.add(data)
            db.session.commit()

            # after commit redirect to this page
            return redirect(url_for('index'))

        except Exception as e:
            return e

    else:
        # retrieve data from database
        # here is problem
        data =  detail.query.all()  #<<<------------------------------- Error
        return render_template('index.html', data=data)




if __name__ == '__main__':
    # here we are telling to 'flask' that integrate db in 'app'
    db.init_app(app)
    # run flask app and you might be thinking debug mean that if you'll do any change in your application so it'll restart server auto
    app.run(debug=True)

我的db.py文件:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

'''here we are init. 'username ' and 'password' because if you'll config
this in your 'main.py application' so it'll not be work
so you have to keep it in a another file and import from there
'''
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:''@localhost/flask'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db = SQLAlchemy(app)

我的index.html文件:

<!--
This is just a simple website it will add your 'name' and 'address', 'phone' in database
-->
<html>

<head>
  <title> First flaks app</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

  <!-- Popper JS -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>

  <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

  <script src="https://kit.fontawesome.com/f6cee5f9d4.js" crossorigin="anonymous"></script>
</head>

<body>
  <h1 class="text-warning text-center">Flask-app-connect to database</h1>
  <div class='container table-responsive w-50 mt-5'>
    <table class="table table-dark table-hover">
      <thead class='bg-info text-dark'>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Phone</th>
        </tr>
      </thead>
      {% for data in data %}
        <tbody>
          <tr>
            <td>{{data.Name}}</td>
            <td>{{data.Email}}</td>
            <td>{{data.Phone}}</td>
          </tr>
        </tbody>
      {% endfor %}
    </table>
  </div>

  <div class="container text-center mt-5">
    <!-- Trigger the modal with a button -->
    <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#myModal">Add to
      database</button>

    <!-- Box Modal -->
    <div class="modal fade" id="myModal" role="dialog">
      <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <h2>Add to database</h2>

          </div>
          <div class="modal-body">
            <!-- Form -->
            <form action="/" method="POST" role="form" class="was-validated">
              <div class="form-group">
                <input type="text" class="form-control" placeholder="Name" name="name" required>
                <div class="valid-feedback">Valid.</div>
              </div>
              <div class="form-group">
                <input type="email" class="form-control" placeholder="Email" name="email" required>
                <div class="valid-feedback">Valid.</div>
              </div>
              <div class="form-group">
                <input class="form-control" type="phone" placeholder="Phone" name="phone" required>
                <div class="valid-feedback">Valid.</div>
              </div>
              <button type="submit" class="btn btn-warning btn-spinner">Commit</button>
            </form>
            <!-- Form end -->
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>

      </div>
    </div>
    <!--End box modal-->

  </div>

</body>

</html>

我希望:

如何从数据库中获取所有数据并通过循环将其放入index.html中。

请让我明白,我在哪里做错了?

了解错误

您看到此错误的原因是因为@moi 提到您的 model 和数据库不匹配。

您的 model 有五个属性idnameemailphonedate 但是,您的数据库在detail中没有名为id的列。

这会在您查询数据库时导致错误,因为 SQLAlchemy 在SELECT语句中指定了它正在查询的每一列。 换句话说,它表示它想要来自idnameemailphonedate列的数据。 不幸的是,数据库没有名为id的列,因此它返回错误。

这很可能是由于您创建了没有id的 model 然后添加了它。 因此,您更新了 model 而不是数据库。

如何解决这个问题

你需要让你的数据库与你的 model 同步。 您将需要从终端运行以下命令。

首先,安装烧瓶迁移。

$ pip install Flask-Migrate

二、配置flask-migrate

为此,至少阅读文档中的示例部分。 Flask 迁移文档

第三,设置迁移文件夹。

$ flask db init

如果这产生Could not locate a Flask application. 错误。 您需要设置FLASK_APP环境变量。 run.py替换为 Flask 应用程序的文件名。

macOS/Linux

$ export FLASK_APP=run.py

Windows

$ set FLASK_APP=run.py

第四,创建您的第一个迁移。

$ flask db migrate

完成此操作后,您应该在/migrations/versions目录中找到一个新文件xxxxxxxxxxxx_.py 这是一个 Alembic 迁移文件。

此时,您有三个选择。

选项 1 :您可以删除您的details表,并让flask-migrate创建一个新表。 您将丢失其中的任何数据。 然后运行upgrade命令。

选项 2 :您可以手动编辑新的 Alembic 迁移文件。 您将需要更改upgrade() function 以便它不会尝试创建新的details表,因为它已经存在,而是添加id列。

选项 3 :您可以从upgrade() function 以及任何其他不在数据库中的列中删除sa.Column("id" sa.Integer()...行。然后在数据库中手动创建一个名为alembic_version的表有一个名为version_num的主键VARCHAR列,长度为 32。然后在alembic_version表中使用上面创建的 alembic 迁移的Revision ID的值创建一个条目。然后再次运行$ flask db migrate 。这将创建第二个alembic 版本文件,应该能够升级您的数据库。

根据您的应用程序的 state 和您的经验水平,我会推荐选项 1。

第五,升级你的数据库。

$ flask db upgrade

阅读文档

我强烈建议阅读有关烧瓶迁移和 Alembic 的文档。 Flask-migrate 是为 flask 应用程序构建的 Alembic 包装器。

Flask 迁移文档

蒸馏器文档

在插入 varchar 值时,如果您忘记添加单引号,则会出现此错误。 以下是错误 - mysql> insert into DemoTable798 values (100,Adam); 错误 1054 (42S22):“字段列表”中的未知列“亚当”

以下对我有用!

import pandas as pd
import sqlalchemy


engine = sqlalchemy.create_engine("mysql+pymysql://root:root@localhost/database name", pool_pre_ping=True)
# then specify the name of the table in the database
df = pd.read_sql_table('table name', engine)
print(df)

您可以在此处找到 sqlalchemy 文档

sqlalchemy.org

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM