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

时间:2019-09-25 12:32:00

标签: python python-3.x flask sqlalchemy flask-sqlalchemy

我建立了一个小型网站,任何人都可以在其中存储“名称,电子邮件,电话”,但是当我从数据库中检索数据时出现此错误。我不为什么?

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

  

sqlalchemy.exc.OperationalError:(MySQLdb._exceptions.OperationalError)(1054,“字段列表”中的未知列“ detail.id”)   [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   从细节]   (此错误的背景位于: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中。

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

3 个答案:

答案 0 :(得分:0)

了解错误

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

您的模型具有五个属性namespace App\Http\Controllers; use Illuminate\Http\Request; use App\form1; class formcontroller extends Controller { public function store(Request $request ){ //dd($request->all()); $form1=new form1; $form1->name=$request->yourname; $form1->save(); $form1->email=$request->email; $form1->save(); $form1->tp=$request->tp; $form1->save(); $form1->heading=$request->subject; $form1->save(); $form1->text=$request->message; $form1->save(); $form1->image=$request->image; $form1->save(); } } idnameemailphone。但是,您的数据库在date表中没有名为id的列。

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

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

如何解决此问题

您需要使数据库与模型同步。您将需要在终端上运行以下命令。

首先,安装flask-migrate。

id

第二,配置flask-migrate

为此至少请阅读文档中的“示例”部分。 Flask Migrate Docs

第三,设置迁移文件夹。

$ pip install Flask-Migrate

如果这产生$ flask db init 错误。您将需要设置Could not locate a Flask application.环境变量。将FLASK_APP替换为Flask应用的文件名。

MacOS / Linux

run.py

Windows

$ export FLASK_APP=run.py

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

$ set FLASK_APP=run.py

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

这时您有三个选择。

选项1 :您可以放下/migrations/versions表,并让details创建一个新表。 您将丢失其中的所有数据。然后运行flask-migrate命令。

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

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

根据您的应用程序状态和您的经验水平,我建议选择1。

第五,升级数据库。

$ flask db migrate

阅读文档

我强烈建议您阅读关于flask-migrate和Alembic的文档。 Flask-migrate是Alembic精心打造的包装瓶,可用于烧瓶应用。

Flask Migrate Docs

Alembic Docs

答案 1 :(得分:0)

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

答案 2 :(得分:0)

以下对我有用!

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