1

I've had a look around SO and couldn't find this particular issue.

So I have an ext config.txt file which is used to obtain values which are stored in variables in the python program. I have a variable in the python that stores the key:values in dictionary form. (the idea is it takes the config settings and performs a sql server query from the program)

my code looks like this (also showing output of the print statements):

driver = config['DRIVER']
server = config['SERVER']
database = config['DATABASE']
trusted = config['Trusted_Connection']

print(driver) # = {ODBC Driver 17 for SQL Server};
print(server) # = server1;
print(database) # = db1;
print(trusted) # = yes

#1. working code
sql_conn = odbc.connect('DRIVER={ODBC Driver 17 for SQL Server}; SERVER=server1; DATABASE=db1;   Trusted_Connection=yes')

#2. non working code
sql_conn = odbc.connect('\''DRIVER='+ str(driver) +  ' SERVER=' + str(server) + ' DATABASE=' + str(database)  +  ' Trusted_Connection='+ str(trusted)+'\'') 

When I try to run the first line, everything works as expected. However when I try with the second line I get:

pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

Is this something to do with the conversion of dict to strings? or perhaps with pyodbc?

dragonfury2
  • 375
  • 5
  • 20

1 Answers1

4

So I managed to find the fix and looks like it was an error with the parsed string:

incorrect:

odbc.connect('\''DRIVER='+ str(driver) +  ' SERVER=' + str(server) + ' DATABASE=' + str(database)  +  ' Trusted_Connection='+ str(trusted)+'\'')

correct:

odbc.connect('DRIVER='+driver+';SERVER='+server+';DATABASE='+database+';Trusted_Connection='+trusted) 
dragonfury2
  • 375
  • 5
  • 20