SQL connection in seperate file? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: SQL connection in seperate file? (/thread-19737.html) |
SQL connection in seperate file? - Tommy - Jul-12-2019 Hey I got a few python scripts in the same folder. They all use a SQL connection. But I have the configured in each of the script files. Can I somehow include the connection info from a single file. So I only need to update the info their if needed? Thanks import pyodbc //to seperate file start server = 'tcp:ip' database = 'db' username = 'user' password = 'pass' cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) cursor = cnxn.cursor() //to seperate file end cursor.execute("SELECT TOP 1 field FROM dbo.table") row = cursor.fetchone() while row: print(row[0]) row = cursor.fetchone() RE: SQL connection in seperate file? - ichabod801 - Jul-12-2019 If you want to modify the connection for different files, I would create a function that returns the cursor. The parameters of the function would be the settings, and the defaults would be the ones you have above. You can have that in another module, import it to each program that needs it, and pass different parameters as needed. I would definitely query the user for their id and password rather than hard coding it as you have above. Also, you should look into the format method of strings, or the even newer f-string syntax (Python 3.6+). |