1. 程式人生 > >錯誤:sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError)

錯誤: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:[email protected]: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 '<Title{}>'.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 <module>
    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裡邊了。要被自己蠢哭了。

好了,至此問題解決。

相關推薦

錯誤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

sqlalchemy.exc.ProgrammingError: (pymysql.err.ProgrammingError)

問題 border 計劃 建立 this datetime pro -i 操作 在我學習flask建立網站時間碰到了一個棘手的問題,就是在我進行操作日誌的更新時間,發現表格建立有點錯誤,導致表缺失,從而報了下面的錯誤sqlalchemy.exc.ProgrammingErr

Redis錯誤jedis.exceptions.JedisDataException: ERR Client sent AUTH, but no password is set

detail protocol 指定 inactive roo max binary load nio 原文鏈接:http://blog.csdn.net/rchm8519/article/details/48347797 redis.clients.util.Pool.

mysql錯誤[Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated

inf 新版 官方 express dep eject .sql nis available 今天遷移django數據庫的時候,跑程序的時候出現這樣的錯誤: [Err] 1055 - Expression #1 of ORDER BY clause is not in GR

redis建立叢集時顯示錯誤 [ERR] Node xxx is not empty. Either the node already knows other no...

純手打,轉載請附上本文網址!!! 在redis叢集配置的最後一步,使用命令報錯[ERR] Node xxx is not empty. Either the node already knows other no... redis-trib.rb create --rep

連線redis報此錯誤ERR Client sent AUTH, but no password is set

from: http://bbs.csdn.net/topics/391824759?page=1 127.0.0.1:6379> auth 123456 ERR Client sent AUTH, but no password is set 設定其密碼 redi

解決 pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on xxxx

在MySQL Server 已經安裝好的情況下, Python 3 使用 pymysql 進行連線資料庫操作時,出現的BUG如下圖:在網上找了資料,看有的說是MySQL沒有開啟,有的說是一些許可權問題,這個問題困擾了我一天,最終我發現,我原來的測試程式碼這樣寫:貌似並不規範,

xcode工程編譯錯誤No architectures to compile for

bis clear 文檔 哪些 i386 提高 href nts b2c 問題 開發環境:xcode6,iPhone6模擬器 xcode工程編譯錯誤:No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active

Linux下使用vi新建文件保存文件時遇到錯誤E212: Can't open file for writing

mage images roo .cn logs 分享 思路 操作 新建 出現E212: Can‘t open file for writing的問題是由於權限問題導致的,解決方法有以下思路: 1、使用root進行登錄,然後再操作。 2、在使用命令時,前面加sudo

主從同步出現一下錯誤Slave_IO_Running: Connecting

主從同步出現一下錯誤:slave_io_running: connecting主從同步出現一下錯誤: Slave_IO_Running: Connecting Slave_SQL_Running: Yes 解決方法: 導致lave_IO_Running 為connecting 的原因主要有

matlab錯誤Subscript indices must either be real positive integers or logicals.

開始 dice int 索引 cal ger 向量 過程 ice matlab錯誤:Subscript indices must either be real positive integers or logicals. 中文解釋:下標索引必須是正整數類型或者邏輯類型

SSH 登錄時出現如下錯誤Disconnected:No supported authentication methods available

.html connected ted tail lan aliyun http html authent https://help.aliyun.com/knowledge_detail/41489.html?spm=5176.product25365.2.1.Ufrmm

python csv文件打開錯誤_csv.Error: line contains NULL byte

sum print question utf-16 null ecs 格式 .cn repl 正常的csv文件讀取如下: #coding:utf-8 import csv csvfilename = ‘demo.csv‘ print u‘########

Apache/2.4.9啟動錯誤AH01630: client denied by server configuration

2.4 -s 錯誤 client ont pop 配置 出現 doc 在升級Yii框架1.11->2.0beta時,PHP升級到5.5。順帶升級Apache2.2.x到2.4.9。把原有vhost配置移植過來,出現Apache啟動錯誤:AH01630: client

qt5 + vs2015自定義控件錯誤undefend interface

自定義 widget 報錯 文件路徑 集成 wid 所在 結果 nbsp 控件中編譯時因為是把所有的單個控件集成到一個lib中,所以會引用#include<QDesignerCustomWidgetInterface>以及#include<QDesigne

WPF錯誤必須使“Property”具有非 null 值。

sta 指定 else 問題 inf led data- roman 取代 這個問題一般出如今Triggers中Property指定的類型為Nullable。解決的方法就是用DataTrigger取代Trigger, 然後用Binding+Converter轉換為詳細非

swagger ui js 錯誤Failed to execute 'serializeToString' on 'XMLSerializer': parameter 1 is not of type 'Node'.

排除法 解決 swa set ring param execute 錯誤 exec 經過排查,引發此錯誤的原因是,表中有一個字段名稱為“NodeName”,應該是在前臺xml解析時引發沖突所致。我的解決辦法是: 修改列名,修改映射。 如下: [Column("NodeNa

qt5.8 鏈接mysql錯誤driver not load

bsp logs ibm targe 轉載 解決方案 解決 target .dll 轉載請註明出處:http://www.cnblogs.com/dachen408/p/7155858.html 問題:qt5.8 鏈接mysql錯誤:driver not load。 解決

error C2065:!錯誤未定義標識符“pBuf);”

str 標識符 error 未定義標識符 image ima 標識 http 使用 error C2065: “pBuf);”: 未聲明的標識符 錯誤原因:第二個括號)使用的是中文符號!還有最後那個分號! 改回來就好了~ 原錯誤: 修

錯誤在maven install是拋出 “1.5不支持diamond運算符,請使用source 7或更高版本以啟用diamond運算符”

list plugin dia artifact mpi config cnblogs 使用 diamond Maven默認用的是JDK1.5去編譯 diamond運算符,有的書翻譯為菱形,有的書寫的是鉆石語法,指的是JDK1.7的一個新特性 List<String