Python Forum

Full Version: Create SQL connection function and validate
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Team,

how to create a sql connection function , and validate if it is successfully connected it or not.
I attempted with below code. code works but not sure whether this is a correct one.


def Create_Connection(server,dbname):
    try:
        str = ('Driver={SQL Server};'
                f'Server={server};'
                f'Database={dbname} ;')
        conn = pyodbc.connect(str)
        print('connected Successfully')
        return conn
    except:
        print('error occured')


if __name__ == "__main__":
    server = 'DESKTOP-GQK64O6'
    dbname = 'Customer'
    con = Create_Connection(server, dbname)
    query = "select * from employee"
An odd use of try/except. It provides no benefit, hides why the connection failed, and crashes shortly after when you try to use the connection. If you catch an exception it is expected that some kind of corrective action is taken. What do you want to do if the connection fails? Printing a message that is less informative than what you would get from the standard error handler is not a good choice.