Python Forum

Full Version: SQL connection in seperate file?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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()
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+).