stacylouis
stacylouis

Reputation: 57

How to do Exception handling for mysql connection in python

I'm new to python , I want to know how to do exception handling in python in a proper way.I want to raise an exception for failure of db connection.I also don't want to include all the lines of code in try block.I want to raise connection failure exception.How to do this?

try:
    conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
                           , db="database")
    mycursor = conn.cursor()
    query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
    val = (x,y,z)
    mycursor.execute(query, val)
    conn.commit()
    conn.close()
    print("Data inserted to db")
except Exception as ex:
    print(ex)

Upvotes: 1

Views: 18086

Answers (2)

Sree
Sree

Reputation: 1758

    conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
                           , db="database")
    mycursor = conn.cursor()
    query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"  
    try:
        mycursor.execute(query, val)
    except MySQLdb.Error, e:
        try:
            print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
            return None
        except IndexError:
            print "MySQL Error: %s" % str(e)
            return None
    except TypeError, e:
        print(e)
        return None
    except ValueError, e:
        print(e)
        return None
    finally:
        mycursor.close()
        conn.close()

Upvotes: 4

balderman
balderman

Reputation: 23815

Something like:

connected = False
try:
    conn = MySQLdb.connect(host="mysql", user="root", passwd="password"
                           , db="database")
    connected  = True
except MySQLError as ex:
    print(ex)
if connected:
    mycursor = conn.cursor()
    query = "INSERT INTO table1(col1,col2,col3)VALUES(%s,%s,%s)"
    val = (x,y,z)
    mycursor.execute(query, val)
    conn.commit()
    conn.close()
    print("Data inserted to db")

Upvotes: 2

Related Questions