错误:sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError)

先晒代码

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import pymysql
app=Flask(__name__)
@app.route('/')
def hello_world():
    return '11hello_world'
app.config['SECRET_KEY']='hard to guess'
app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:123456@localhost:3306/news_title'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True
db=SQLAlchemy(app)

class Title(db.Model):
    __tablename__='title'
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(256),unique=True)
    def __ref__(self):
        return ''.format(self.name)
db.create_all()
title_one=Title(name='ddddddd')
title_two=Title(name='aaaaaa')
title_three=Title(name='aaaaaa')
db.session.add_all([title_one,title_two,title_three])
db.session.commit()

if __name__=='__main__':
     app.run()

运行结果显示:

JudydeMacBook-Air:python judy$ python o1.py

Traceback (most recent call last):
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
    context)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
    cursor.execute(statement, parameters)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/cursors.py", line 166, in execute
    result = self._query(query)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/cursors.py", line 322, in _query
    conn.query(q)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/connections.py", line 835, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/connections.py", line 1019, in _read_query_result
    result.read()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/connections.py", line 1302, in read
    first_packet = self.connection._read_packet()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/connections.py", line 981, in _read_packet
    packet.check_error()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/connections.py", line 393, in check_error
    err.raise_mysql_exception(self._data)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/err.py", line 107, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.IntegrityError: (1062, "Duplicate entry 'aaaaaa' for key 'name'")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "o1.py", line 26, in
    db.session.commit()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 157, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 874, in commit
    self.transaction.commit()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 461, in commit
    self._prepare_impl()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 441, in _prepare_impl
    self.session.flush()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2139, in flush
    self._flush(objects)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2259, in _flush
    transaction.rollback(_capture_exception=True)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__
    compat.reraise(exc_type, exc_value, exc_tb)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 187, in reraise
    raise value
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2223, in _flush
    flush_context.execute()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 389, in execute
    rec.execute(self)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 548, in execute
    uow
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 181, in save_obj
    mapper, table, insert)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 835, in _emit_insert_statements
    execute(statement, params)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement
    compiled_sql, distilled_params
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
    context)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1393, in _handle_dbapi_exception
    exc_info
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
    reraise(type(exception), exception, tb=exc_tb, cause=cause)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 186, in reraise
    raise value.with_traceback(tb)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
    context)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
    cursor.execute(statement, parameters)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/cursors.py", line 166, in execute
    result = self._query(query)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/cursors.py", line 322, in _query
    conn.query(q)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/connections.py", line 835, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/connections.py", line 1019, in _read_query_result
    result.read()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/connections.py", line 1302, in read
    first_packet = self.connection._read_packet()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/connections.py", line 981, in _read_packet
    packet.check_error()
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/connections.py", line 393, in check_error
    err.raise_mysql_exception(self._data)
  File "/Users/judy/anaconda/lib/python3.6/site-packages/pymysql/err.py", line 107, in raise_mysql_exception
    raise errorclass(errno, errval)
sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "Duplicate entry 'aaaaaa' for key 'name'") [SQL: 'INSERT INTO title (name) VALUES (%(name)s)'] [parameters: {'name': 'aaaaaa'}]

问题所在:

sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "Duplicate entry 'aaaaaa' for key 'name'") [SQL: 'INSERT INTO title (name) VALUES (%(name)s)'] [parameters: {'name': 'aaaaaa'}]

分析问题:

这段话大概的意思是说我的一个键值重复了。excuse me?键值不能重复?感觉怪怪的。


解决方法:

不管了,我先按照提示来改一下把title_tree 的name改为aaaaa99,运行结果是正确的。

追根溯源

title_one=Title(id=6,name='ddddddd')
title_two=Title(id=5,name='aaaaaa')
title_three=Title(id=4,name='aaaaa999')
name键值没有改,把id键值手动递增。出现的错误跟以上一样。


title_one=Title(id=6,name='ddddddd1')
title_two=Title(id=5,name='aaaaaa1')
title_three=Title(id=4,name='aaaaa9991')

id键值没有改,改了name键值,可以了。尼玛怎么回事?

name不能重复?不应该啊!难道?

回去看一下代码,oh my gold。

name=db.Column(db.String(256),unique=True)
把unique=True写到name里边了。要被自己蠢哭了。

好了,至此问题解决。



你可能感兴趣的:(python)