1. 概要
Pythonコード実施時、try:の範囲でエラーが発生すれば、exceptに処理が移る。
下記のコードでは、エラーコードが"sqlite3.IntegrityError"であれば、except以下の
コードを実施する流れになっている。
test.py(関係あるコードのみを掲載)
if __name__=='__main__':
try:
(略)
except sqlite3.IntegrityError as ex:
if "UNIQUE constraint failed: STOCK_INFO.STOCK_NUM" in ex:
print("ERROR:{}".format(ex))
上記のコードを実施するとエラーが発生する。
root@2a1627805ea9:/home/stock# python3 sqltest.py 13
7
UNIQUE constraint failed: STOCK_INFO.STOCK_NUM
Traceback (most recent call last):
File "sqltest.py", line 103, in <module>
cur.execute(insert_sql,STOCK_INFO)
sqlite3.IntegrityError: UNIQUE constraint failed: STOCK_INFO.STOCK_NUM
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "sqltest.py", line 127, in <module>
if "UNIQUE constraint failed: STOCK_INFO.STOCK_NUM" in ex:
TypeError: argument of type 'IntegrityError' is not iterable
2. 解決法
エラーの原因はこちらに分かりやすく書かれてあり、この情報に従い
ex → str(ex)を書き換えれば正常に動作するようになりました。
test.py(修正後)
if __name__=='__main__':
try:
(略)
except sqlite3.IntegrityError as str(ex): # ex → str(ex)を書き換える。
if "UNIQUE constraint failed: STOCK_INFO.STOCK_NUM" in ex:
print("ERROR:{}".format(ex))