无法使用 PYODBC python 库连接到 SQL Server

问题描述 投票:0回答:0

我正在尝试连接到 SQL Server 数据库(位于虚拟机中,但我使用的用户是 db_owner,无需在虚拟机内部即可连接)来查询数据库并获取结果。该脚本的作用是检查数据库是否被扰乱。

import pandas as pd
import pyodbc
import cx_Oracle
import csv

# Load the data from the Excel file
df = pd.read_excel('DatabasesList.xlsx')
print (df)

cx_Oracle.init_oracle_client(lib_dir=r"C:\oracle\instantclient_21_10")
first_name_to_check = 'XXXX'

# Open the CSV file
with open('results.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    # Write the headers
    writer.writerow(['Database', 'Host', 'Result'])

    # Loop over the rows of the dataframe
    for _, row in df.iterrows():
        username = row['Username']
        password = row['Password']
        database = row['Database']
        host = row['Host']
        rdbms = row['Rdbms']

        conn = None
        # Connect to the database depending on the RDBMS
        if rdbms == 'DB2':
            continue
        elif rdbms == 'MsSql':
            conn_str = f"DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={host};DATABASE={database};UID={username};PWD={password};"
            try:
                conn = pyodbc.connect(conn_str)
            except pyodbc.OperationalError:
                print(f"Could not connect to {host} - {database}. Moving to next database.")
                continue
        else:
            print(f"No connection process implemented for {rdbms} - {database} - {host}.")
            continue

        print("Executing in: ", database)
        if conn is not None:
            # You can now use `conn` to query the database
            cursor = conn.cursor()
            cursor.execute(f"SELECT COUNT(*) FROM {username}.CUSTOMER WHERE FIRST_NAME LIKE '%{first_name_to_check}%'")

            # Fetch the result
            result = cursor.fetchone()[0]

            # Write the results to the CSV file
            writer.writerow([database, host, result])

            # Close the connection
            cursor.close()
            conn.close()

在Try中出现错误,错误信息为:

('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [1326].  (1326) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (1326)')

请注意,数据框中的每个条目都会发生这种情况。

更新

  • Trusted_Connection = True 不起作用。
python sql-server pyodbc
© www.soinside.com 2019 - 2024. All rights reserved.