1

I am really confused by writing a config file for connecting python to SQL Server specifically using pyodbc. I have wrote a class which connects to the database. However my boss keeps yelling at me the connection should be in a config file and I'm struggling with how to do it and even understand it. So far my code is below. As you can tell I'm new to coding so can someone please help me understand the purpose of a config file and help me with the process?

import pyodbc
import sqlalchemy as sa
import urllib
import pandas as pd


class SQL_Database:

    def __init__(self, database, driver='SQL Server', server='.\TEST_SERVER'):
        self.driver = driver
        self.server = server
        self.database = database

    def create_server_connection(self):
        connection = None
        try:
            connection = pyodbc.connect(f'Driver={self.driver};'
                                        f'Server={self.server};'
                                        f'Database={self.database};'
                                        'Trusted_Connection=yes;')
            print("MySQL Database connection successful")
        except pyodbc.Error as err:
            print("Connection failed")
        return connection


conn = SQL_Database(database='index_changes').create_server_connection()


10
  • Oops, are you connecting to MS SQL Server or MySQL? Now I'm a bit confused. Commented Sep 22, 2021 at 15:12
  • I am trying to connect to MS SQL Server Commented Sep 22, 2021 at 15:17
  • Just what I thought. But the print("MySQL Database connection successful") made me confused. Commented Sep 22, 2021 at 15:18
  • ahhh sorry i have changed that in my code now thanks for picking that up Commented Sep 22, 2021 at 15:19
  • Does this answer your question? import my database connection with python Commented Sep 22, 2021 at 15:37

1 Answer 1

1

Here's an example for loading the values from a json file.

  1. Create a config file named config.json.
{
"driver": "DriverName",
"server": "ServerName",
"database": "DatabaseName"
}
  1. Read in the config parameters in your class.
import pyodbc
import json

class SQL_Database():

    def __init__(self):

        with open('path/to/config.json','r') as fh:
            config = json.load(fh)

        self.driver = config['driver']
        self.server = config['server']
        self.database = config['database']

        connection = pyodbc.connect(
        f'Driver={self.driver};'
        f'Server={self.server};'
        f'Database={self.database};'
        )

SQL_Database()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.