Python 3.6.5的坑 pymysql warning

Posted luoyueren

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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(" .... 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 FilesPython36libsite-packagespymysqlcursors.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的主要内容,如果未能解决你的问题,请参考以下文章

Python 3.6.5的坑 AES padding

python连接mysql数据库之MySQLdb/pymysql

稍微记录下Django2.2使用MariaDB和MySQL遇到的坑

用 pymysql 打印 MySQL/MariaDB 的所有库名表名和字段名

django的mysqldb的坑

Pycharm添加Mysql數據庫的坑