Python 3.6.5的坑 pymysql warning
import pymysql
#連接數據庫
def ConnectDB():
db = None
config={
"host":"127.0.0.1",
‘port‘:3306,
"user":"xxxxxx",
"password":"*************",
"database":"xxxxxxx",
‘charset‘:‘utf8mb4‘,
}
try:
db = pymysql.connect(**config)
except Exception as e:
error = traceback.format_exc()
print("\n.... Failed to connect database:")
print(error)
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
Python 3.6.5的坑 pymysql warning