Python MySQLdb exit on duplicate entry

706 Views Asked by At

I want to exit the program on duplicate entry this is what I have done without success:

I would like to handle the error but don't know how and haven't found information about it.

def connection():

    global servername, username, password, dbname

    con = mdb.connect(servername, username, password, dbname)

    return con;


def insert_vulnerabilities (CVE,Description,P_Date,U_Date,Score,Type):



    con = connection()



    with con:

        cur = con.cursor()


        try:
            cur.execute("INSERT INTO Vulnerabilities_test(CVE,Description,P_Date,U_Date,Score,Type) VALUES(%s,%s,%s,%s,%s,%s)",(CVE,Description,P_Date,U_Date,Score,Type))
            con.commit()
        except:

            sys.exit(0)

Thank you in advance.

1

There are 1 best solutions below

0
On
import sys
...
...
...

    try:
        write_cursor.execute(write_operation)
        db_writer.commit()
    except IntegrityError as ie:
        print("Duplicate key found. Exiting.")
        sys.exit(1)