Python – Database – SQLServer – Exception Handling

#my first python program
import _mssql
import sys
import os
import traceback

objDBConn = None

try:

    objDBConn = _mssql.connect(server='DBLAB', user='myDBUser', password='amer1ca', database='sales')

    sqlDBStoredProcedure = "usp_getMonthlySales"

    objDBConn.execute_query(sqlDBStoredProcedure);

    for row in objDBConn:

        print "ObjectName=%s NumberOfRecords=%d" % (row['item'], row['numberofItems'])

except _mssql.MssqlDatabaseException, ex:
    exc_type, exc_obj, exInfo = sys.exc_info()
    sourcefileName = os.path.split(exInfo.tb_frame.f_code.co_filename)[1]
    sourcefileLineNumber = exInfo.tb_lineno
    print "DB Database Exception (Message)  :   " + ex.message
    print "DB Database Exception (Number)   :   %d" % (ex.number)  
    print "                    Source Code  :   " + sourcefileName
    print "                    Source Line #:   %d" % ( sourcefileLineNumber) 
    print "Stack Trace:"
    traceback.print_exc()   

except:

	print "Error ", sys.exc_info()[0]

finally:

    if (objDBConn) is not None:

       objDBConn.close()

References:

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s