i am trying to connect to SQL Server database (which is located in a VM, but the user i am using is db_owner and can connect without being inside the VM) to Query the database and get a result back. What does the script do is to check if the database is scrambled.
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 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()
The error Occurs in the Try which the error message is:
('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)')
Note that this happens for every entry in the Dataframe.
Trusted_Connection = Yes;
did not work.
A dataframe looks like: Dataframe Example