Here is a problem that I am facing while connecting to SQL Server database using python/adodbapi.
We have a SQL Server test database that is in a different domain using the following method.
runas /netonly /user:<domain>\<userid> "C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\Ssms.exe"
I am able to manually login to SQL database using SQL Server Management Studio but not able to make a connection programmatically.
Here's what I've tried so far:
def query_sql_server_with_windows_authentication(server_name, database_name, username, password, sql_query, output_file_path, delimiter='|', header_flag=True):
conn = adodbapi.connect("PROVIDER=SQLOLEDB;Data Source={0};Database={1}; trusted_connection=yes;UID={2};PWD={3};".format(server_name, database_name, username, password))
cursor = conn.cursor()
cursor.execute(sql_query)
output_file_path = os.path.abspath(output_file_path)
with open(output_file_path,'w') as fout:
if header_flag:
column_names = [item[0] for item in cursor.description]
header = delimiter.join(column_names)
fout.write(header + "\n")
for row in cursor:
columns = [str(column).encode('UTF-8') for column in row]
fout.write(delimiter.join(columns) + "\n")
print("Completed. Returning output file {}".format(output_file_path))
return output_file_path
Output : Error received as follows:
adodbapi.apibase.OperationalError: (com_error(-2147352567, 'Exception occurred.', (0, u'Microsoft OLE DB Provider for SQL Server', u'Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.', None, 0, -2147467259), None), 'Error opening connection to "PROVIDER=SQLOLEDB;Data Source=<databasehost>,<port>;Database=testdb; trusted_connection=yes;UID=domain\\username;PWD=password;"')
Is there anyway to get around this connectivity problem?
Here is my answer to the question:
Hope this helps someone in the future.