Most examples I can find showing a full MSSQL connection method with Python are out of date as of a few months back, thanks in part to some optimisations in SQLAlchemy 1.3. I'm trying to replicate what I can see in the documentation.
I'm having trouble getting SQLAlchemy connected to MSSSQL Server using pyodbc.
I have a local SQL server, reachable from SQL Server Management Studio on: #DESKTOP-QLSOTTG\SQLEXPRESS
The Database is: TestDB
The username, for this example is: TestUser
The password, for this example is: TestUserPass
I'm wanting to run a test case (cases?) of importing a pandas dataframe into the MSSQL database in order to work out what is the speediest way of doing things. However, the purpose of this question is around connectivity.
Credit: I borrowed some code from Gord for the dataframe/update here.
import pandas as pd
import numpy as np
import time
from sqlalchemy import create_engine, event
from urllib.parse import quote_plus
# for pyodbc
#engine = create_engine('mssql+pyodbc://TestUser:TestUserPAss@DESKTOP-QLSOTTG\\SQLEXPRESS:1433/TestDB?driver=ODBC+Driver+17+for+SQL+Server', fast_executemany=True)
engine = create_engine("mssql+pyodbc://TestUser:TestUserPass@DESKTOP-QLSOTTG\\SQLEXPRESS:1433/TestDB?driver=ODBC+Driver+13+for+SQL+Server", fast_executemany=True)
# test data
num_rows = 10000
num_cols = 100
df = pd.DataFrame(
[[f'row{x:04}col{y:03}' for y in range(num_cols)] for x in range(num_rows)],
columns=[f'col{y:03}' for y in range(num_cols)]
)
t0 = time.time()
df.to_sql("sqlalchemy_test", engine, if_exists='replace', index=None)
print(f"pandas wrote {num_rows} rows in {(time.time() - t0):0.1f} seconds")
The error that I'm receiving is the following. I'm going to assume that the server 'actively refusing the connection' is because my connection string is somehow messed up, but I cant seem to see why.:
OperationalError: (pyodbc.OperationalError) ('08001', '[08001] [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: No connection could be made because the target machine actively refused it.\r\n (10061) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 13 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. (10061)')
(Background on this error at: http://sqlalche.me/e/13/e3q8)
The database and user are connectable from SQL Server Management Studio.*
Any ideas on what I might be missing?
Notes:
- Changing DESKTOP-QLSOTTG\SQLEXPRESS:1433 to DESKTOP-QLSOTTG:1433 didn't change the error
- Changing DESKTOP-QLSOTTG\SQLEXPRESS:1433 to localhost:1433 didn't change the error
- Changing DESKTOP-QLSOTTG\SQLEXPRESS:1433 to localhost\SQLEXPRESS:1433 didn't change the error