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
  SSAS Connection ray67 1 266 Feb-28-2019, 05:34 PM
Last Post: Larz60+
  cefpython3. JS and Python connection ioprst 0 281 Jan-30-2019, 09:04 AM
Last Post: ioprst
  Connection with SQL Server DionisiO 0 215 Jan-27-2019, 01:11 PM
Last Post: DionisiO
  Does Python sqlite3 detect connection errors zatlas1 6 442 Jan-18-2019, 06:02 AM
Last Post: zatlas1
  Enable & Disable Wireless connection by using python aniyanetworks 9 1,712 Jan-15-2019, 04:32 AM
Last Post: aniyanetworks
  Connection with firebird using python nick722 0 603 Nov-23-2018, 03:40 PM
Last Post: nick722
  Socket connection and thread tracking... MuntyScruntfundle 2 411 Oct-21-2018, 02:55 AM
Last Post: Skaperen
  mysql connection pool? MuntyScruntfundle 0 411 Oct-20-2018, 07:36 PM
Last Post: MuntyScruntfundle
  mysql db connection using python sunstar20 13 2,369 Aug-04-2018, 09:08 AM
Last Post: vishalhule
  Python Informix connection BLT 1 1,906 Jun-07-2018, 08:54 PM
Last Post: Larz60+

Forum Jump:

Users browsing this thread: 1 Guest(s)