Home > database >  config file - connecting python to SQL Server via pyodbc
config file - connecting python to SQL Server via pyodbc

Time:09-23

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()


CodePudding user response:

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()
  • Related