Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 SQL connection in seperate file?

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?


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:
        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+).
Craig "Ichabod" O'Brien -
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures


Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  how to seperate words from string zarize 2 113 Aug-29-2019, 08:23 AM
Last Post: zarize
  Seperate entities in text file bigdazza 1 521 Jun-02-2018, 03:15 PM
Last Post: snippsat
  how to start a seperate thread for every item in a list lravikumarvsp 1 551 May-31-2018, 08:07 AM
Last Post: ThiefOfTime
  I have an array, how can I search a seperate file for the contents of my array? Mr_Keystrokes 0 709 Mar-13-2018, 02:25 PM
Last Post: Mr_Keystrokes

Forum Jump:

Users browsing this thread: 1 Guest(s)