Home > front end >  SQL connection string into function
SQL connection string into function

Time:03-02

I am trying to put a connection string into a function for database connection:

conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
                      'Server=trve-tl'
                      'Database=team;'
                      'Trusted_Connection=yes;')

with open("bike.sql", "r") as file:
    query = file.read()

I have attempted to create a function as follows:

def get_connection(server:str, Database:str)->str:
    global conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
                      'Server=' server ';'
                      'Database=' Database ';'
                      'Trusted_Connection=yes;')
    return conn

    

I get the following error:

global conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};' ^ SyntaxError: invalid syntax

CodePudding user response:

You need to remove the 'global' keyword from your conn variable declaration, then store the output of the function in a new variable.

def get_connection(server:str, Database:str)->str:
conn = pyodbc.connect('Driver={SQL Server Native Client 11.0};'
                  'Server=' server ';'
                  'Database=' Database ';'
                  'Trusted_Connection=yes;')
return conn

then call it something like this

cn = get_connection("localhost","MyDB")
cn.close()
  • Related