Python Forum
SQL connection in seperate file?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
SQL connection in seperate file?
#1
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()
Reply
#2
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 - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Input network device connection info from data file edroche3rd 6 912 Oct-12-2023, 02:18 AM
Last Post: edroche3rd
  How to seperate dict value? ilknurg 2 1,302 Mar-11-2022, 10:48 AM
Last Post: perfringo
  Serial connection connection issue Joni_Engr 15 7,828 Aug-30-2021, 04:46 PM
Last Post: deanhystad
  Two separate dataframes, two seperate programs stylingpat 2 1,950 Apr-28-2021, 07:56 PM
Last Post: stylingpat
  Seperate output buffer matt_the_hall 2 2,314 Mar-15-2021, 08:44 PM
Last Post: matt_the_hall
  Pyinstaller create this error :“File ”multiprocessing\connection.py“, line 691 Formationgrowthhacking 2 3,573 Apr-30-2020, 10:26 AM
Last Post: buran
  how to seperate words from string zarize 2 2,040 Aug-29-2019, 08:23 AM
Last Post: zarize
  Seperate entities in text file bigdazza 1 2,797 Jun-02-2018, 03:15 PM
Last Post: snippsat
  how to start a seperate thread for every item in a list lravikumarvsp 1 2,874 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 2,322 Mar-13-2018, 02:25 PM
Last Post: Mr_Keystrokes

Forum Jump:

User Panel Messages

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