flask中出现:IntegrityError: (_mysql_exceptions.IntegrityError) (1062, "Duplicate entry

先上代码:

#coding:utf-8
from flask import Flask, render_template, flash, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

app=Flask(__name__)

#项目配置信息
class Config(object):
    DEBUG=True
    #连接mysql数据的信息
    SQLALCHEMY_DATABASE_URI="mysql://root:[email protected]:3306/author_book"
    #让sqlalchemy跟踪数据库的修改
    SQLALCHEMY_TRACK_MODIFICATIONS=True
    SECRET_KEY="DSKFSDJKFHSKDKCNIASNCFIOFASNDCIOSANCIOSNIOCN"


app.config.from_object(Config)

#创建sqlalchemy数据库的连接对象
db=SQLAlchemy(app)


class Author(db.Model):
    __tablename__="tbl_authors"
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(64),unique=True)
    books=db.relationship("Book",backref="author")

class Book(db.Model):
    __tablename__="tbl_books"
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(64),unique=True)
    author_id=db.Column(db.Integer,db.ForeignKey('tbl_authors.id'))

class AuthorBookForm(FlaskForm):
    author_name=StringField(label=u"作者",validators=[DataRequired()])
    book_name=StringField(label=u"书籍",validators=[DataRequired()])
    submit=SubmitField(label=u"提交")

@app.route('/',methods=["GET","POST"])
def index():
    form=AuthorBookForm()
    error_msg = ""
    if form.validate_on_submit():
        author_name=form.author_name.data
        book_name=form.book_name.data


        author_count=Author.query.filter_by(name=author_name).count()

        if author_count==0:
            author=Author(name=author_name)
            db.session.add(author)
            db.session.commit()
            book_count=Book.query.filter_by(name=book_name).count()
            if book_count==0:
                book=Book(name=book_name,author_id=author.id)
                db.session.add(book)
                db.session.commit()
            else:
                error_msg=(u"该图书已经存在")
                db.session.delete(Author.query.filter_by(name=author_name)[0])
        else:

            author=Author.query.filter_by(name=author_name)[0]

            book = Book(name=book_name, author_id=author.id)
            db.session.add(book)
            db.session.commit()


    # 查询数据库
    authors = Author.query.order_by(Author.id.desc()).all()

    return render_template("author_book.html",authors=authors,form=form,error_msg=error_msg)


@app.route("/delete_book/")
def delete_book(id):
    book=Book.query.get(id)
    db.session.delete(book)
    db.session.commit()

    return redirect(url_for("index"))

if __name__ == '__main__':
    # #删除数据库中所有的表
    # db.drop_all()
    #创建所有的表
    db.create_all()

    au_xi=Author(name="我吃西红柿")
    au_qian=Author(name="萧潜")
    au_san=Author(name="唐家三少")

    db.session.add_all([au_xi,au_qian,au_san])
    db.session.commit()

    bk_xi=Book(name='吞噬星空',author_id=au_xi.id)
    bk_xi2=Book(name="寸芒",author_id=au_qian.id)
    bk_qian=Book(name="缥缈之旅",author_id=au_qian.id)
    bk_san=Book(name="冰火魔厨",author_id=au_san.id)

    db.session.add_all([bk_qian,bk_san,bk_xi,bk_xi2])
    db.session.commit()
    app.run()

运行的时候,我先插入了一个作者和对应的一本书,点击提交,然后数据不变再次点击提交的时候,出现如下错误:
flask中出现:IntegrityError: (_mysql_exceptions.IntegrityError) (1062,

分析了一下原因,这是因为我在定义数据库字段的时候,设置了字段值为唯一性,现在提交了相同的数据,但是在程序中没有处理,所以才会报错!解决办法如下:
flask中出现:IntegrityError: (_mysql_exceptions.IntegrityError) (1062,

这样就解决了这个问题。当然,这种类型的报错不一定是我这个原因产生的,可以根据自己的程序进行排查。

你可能感兴趣的:(Flask)