Monday, February 18, 2019

py0012 : try catch in Python / DB connection in try catch

try catch is preliminary to add in your code, other wise if it break in between it looks ugly when error come to end user. To make code clean and show user friendly error you can use try catch, see one of the example below when database connection.

Earlier when database connection fails, it show red color unexpected error and since this file is being in use further so need to use try catch which will return something so that further can be used as if else for any type of condition

import os
import pyodbc
from configuration import *

try:
    crsrconn = pyodbc .connect("Driver={SQL Server Native Client 11.0};"
                                "Server="+ServerName+";"
                                "Database="+DatabaseName+";"
                                "Trusted_Connection=yes;"
                                "pwd="+Password+";")
    cursor = crsrconn.cursor()
    cursor.execute('SELECT count(*) rn FROM *****')
    for row in cursor:

        if row != 0:
            def t(): return 1
            print ('1')
        #else:
         #   def t(): return 0
          #  print ('0')

except pyodbc.Error as err:
    print("DBConnectionError")
    def t(): return ("DBConnectionError")

No comments:

Post a Comment

web stats