Python Forum
Create SQL connection function and validate
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create SQL connection function and validate
#1
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"
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Bug New to coding, Using the zip() function to create Diret and getting weird results Shagamatula 6 1,456 Apr-09-2023, 02:35 PM
Last Post: Shagamatula
  validate large json file with millions of records in batches herobpv 3 1,280 Dec-10-2022, 10:36 PM
Last Post: bowlofred
  python create function validation mg24 1 847 Nov-15-2022, 01:57 AM
Last Post: deanhystad
  create my exception to my function korenron 2 797 Nov-09-2022, 01:50 PM
Last Post: korenron
  Create a function for writing to SQL data to csv mg24 4 1,177 Oct-01-2022, 04:30 AM
Last Post: mg24
Sad how to validate user input from database johnconar 3 1,934 Sep-11-2022, 12:36 PM
Last Post: ndc85430
  Serial connection connection issue Joni_Engr 15 8,100 Aug-30-2021, 04:46 PM
Last Post: deanhystad
  How to define a function to create a resorted list? sparkt 6 2,848 Aug-08-2020, 04:10 PM
Last Post: sparkt
  Unable to Validate csv blanck data and write in csv prashant18 0 1,545 Jul-25-2020, 12:08 PM
Last Post: prashant18
  How to make this function general to create binary numbers? (many nested for loops) dospina 4 4,439 Jun-24-2020, 04:05 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020