Python 3.6.5的坑 pymysql warning

import pymysqlmysql

#鏈接數據庫 sql

def ConnectDB():數據庫

db = None
config={spa

"host":"127.0.0.1",
'port':3306,
"user":"xxxxxx",
"password":"*************",
"database":"xxxxxxx",
'charset':'utf8mb4',orm

}string


try:it

db = pymysql.connect(**config)io

except Exception as e:form

error = traceback.format_exc()
print("\n.... Failed to connect database:")
print(error)import

if not db:

sys.exit(0)
return db


#主程序

try:

db = ConnectDB()
cursor = db.cursor()
sql = 「INSERT INTO ...」
arg = ("xxx","xxx", ...)
cursor.execute(sql, arg)
db.commit()

except Exception as e:

error = traceback.format_exc()
print(error)
db.rollback()

"""
#--------------------------------------
#若是這個時候出現錯誤:
C:\Program Files\Python36\lib\site-packages\pymysql\cursors.py:167: Warning: (1300, "Invalid utf8mb4 character string: 'C191D4'")
result = self._query(query)
#這個錯誤Exception捕捉不到,"Warning: (1300, ..." 對INSERT結果幾乎沒有影響,要插入的內容還會保存到數據庫裏,MySQL沒有db.rollback()

#若是要捕捉pymysql, 要用到這個庫:
from warnings import filterwarnings
filterwarnings("error",category=pymysql.Warning)
#而後「except Exception as e:「變成
except pymysql.Warning as e:
print(e)
#可是坑在這裏了,一旦出現pymysql.Warning, 就會觸發db.rollback(),數據不會被保存!!
#--------------------------------------
"""

from warnings import filterwarnings
filterwarnings("error",category=pymysql.Warning)

 #主程序:

try:

db = ConnectDB()
cursor = db.cursor()
sql = 「INSERT INTO ...」
arg = ("xxx","xxx", ...)
cursor.execute(sql, arg)
db.commit()

except pymysql.Warning as e:

error = traceback.format_exc()
print(error)


#db.rollback() 這裏不用寫db.rollback(), 多是這模塊warnings的filterwarnings默認就是要這樣作的

#Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32

#pymysql 0.9.2

相關文章
相關標籤/搜索