title: How to do Exception handling for mysql connection in python
body: <p>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?</p>
  
  <pre><code>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)
  </code></pre>