python中检测mysql的主键唯一性异常
时间:2021-07-01 10:21:17
帮助过:16人阅读
os
import mysql_operate.mysql_connect as mysql
import re
def insert(user_email, nickname):
cnx =
mysql.connect()
cur =
cnx.cursor()
# sql = "INSERT INTO users VALUES (%d, %d)"
try:
# print("正在尝试......")
cur.execute(
"INSERT INTO users VALUES(%r ,%r)" %
(user_email, nickname))
print(
"插入成功!")
mysql.disnect(cnx)
return 1
except Exception as ER_DUP_ENTRY:
#except Exception as e:
# print("发生错误,错误信息为:", e)
# mmm = ‘1062 (23000): Duplicate entry \‘[\S]*\‘ for key \‘PRIMARY\‘‘
# print(str(e))
# print(mmm)
#
#
#
# if(re.search(mmm , str(e))):
# print("该用户已注册!")
print(
"成功了")
mysql.disnect(cnx)
return 0
mysql.disnect(cnx)
if __name__ ==
"__main__":
email =
"test_email1@qq.com"
nickname =
"hahahaha"
insert(email, nickname)
2.如上注释的代码,直接检测异常的字符串进行正则匹配,关于如何匹配该异常字符串可以找我上一篇随笔,python正则表达式的艰辛路
python中检测mysql的主键唯一性异常
标签:表达式 users for mmm nic entry 两种方法 异常 成功