1

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)
1
  • well, since you connect to mysql on second line you can just "try-except" this particular line, no need to handle other lines for connection failures Commented Mar 5, 2019 at 16:38

2 Answers 2

4
    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()
Sign up to request clarification or add additional context in comments.

Comments

2

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.