首页 > 解决方案 > 使用 SSMS 和 Windows 凭据将 Python 连接到 SQL Server

问题描述

这是我在使用 python/adodbapi 连接到 SQL Server 数据库时遇到的问题。

我们有一个使用以下方法位于不同域中的 SQL Server 测试数据库。

runas /netonly /user:<domain>\<userid> "C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\Ssms.exe"

我可以使用 SQL Server Management Studio 手动登录 SQL 数据库,但无法以编程方式建立连接。

这是我到目前为止所尝试的:

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

输出:收到的错误如下:

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;"')

有没有办法解决这个连接问题?

标签: pythonsql-serveradodbapi

解决方案


这是我对这个问题的回答:

def query_sql_server(dbHost, dbPort, dbName, dbUser, dbPassword, sqlQuery, outputFile, delimiter='|', headerFlag=True):
outputFile = os.path.abspath(outputFile)
with pymssql.connect(host=dbHost, port=dbPort, user=dbUser, password=dbPassword, database=dbName) as conn:
    cursor = conn.cursor()
    sql = sqlQuery.encode('utf-8')
    cursor.execute(sql)
    with codecs.open(outputFile, 'w', encoding='utf-8') as fout:
        if headerFlag == 'True':
            column_names = [item[0].encode('utf-8') for item in cursor.description]
            header = delimiter.join(column_names)
            fout.write(u'{}{}'.format(header, "\n"))

        for row in cursor:
            try:
                columns = [unicode(column or '') for column in row]
                fout.write(u'{}{}'.format(delimiter.join(columns), "\n"))
            except UnicodeEncodeError:
                print("UnicodeEncodeError- Skipping this record {}".format(row))

    print("Completed and output is available in {}".format(outputFile))
    return outputFile

希望这对将来的某人有所帮助。


推荐阅读