首页 > 技术文章 > python中检测mysql的主键唯一性异常

foreverlin 2019-05-09 20:47 原文

有两种方法:

1.直接检测是什么异常(查mysql文档找出异常代码)

import 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正则表达式的艰辛路

推荐阅读