PYODBC can't connect to SQL Express instance - python

I'm running an instance of SQL Server Express 2017 on my computer. I am attempting to connect to it with the following connection string:
"Driver=ODBC Driver 13 for SQL Server;Server=COMPUTERNAME\\SQLEXPRESS,1433;Database=databasename;Uid=testuser;Pwd=testpassword;Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;"
I have successfully connected to the server manually using those connections and SQL Server Authentication using SQL Server Management Studio.
Firewall shouldn't be an issue as it's a locally hosted server, but I've opened port 1433 for inbound and outbound connections anyway.
This connection string format has worked in the past with a database hosted on Azure (which I can no longer afford to do).
The error message:
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]Invalid connection string attribute (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)')
Any more suggestions?

I'm going to answer this question in case someone else finds it, even though it's old.
What worked pretty well for me was:
Finding out the port used by the SQL Express instance (which in my case turned out to be good 'ol 1433)
Using Network Library=DBMSSOCN to avoid issues regarding named instances (couldn't make it work that way)
How?
Doing it this way:
pyodbc.connect('driver={SQL Server Native Client 11.0};server='+DBIPAddress+';port='+DBPort+';Network Library=DBMSSOCN;database='+DBName+';uid='+DBUser+';pwd='+DBPass)
Where
DBIPAddress is the IP address of the SQL Server server
DBPort is the port
DBName is the name of the database you're trying to connect to
DBUser is the username you're using
DBPass is the password
I guess you could use {SQL Server} driver also, but I haven't tried. What we're doing is forcing a connection using the IP and port regardless of the existence of a named instance.

Related

Python - SQL ODBC login with active directory authentication using user name & password

Is there a way to login to SQL server from Linux server using "ODBC Driver 17 for SQL Server" by passing active directory UID & PWD (not using Trusted_Connection=Yes option).
I tried with below connection parameters but getting error:
"Driver=ODBC Driver 17 for SQL Server;MultiSubnetFailover=Yes;UID=;PWD=;Server=;Database=;"
Error: Login failed
"Driver=ODBC Driver 17 for SQL Server;MultiSubnetFailover=Yes;UID=;PWD=;Server=;Database=;Authentication=ActiveDirectoryPassword";
Error: SSL Provider: SSL routines: [error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed: self signed certificate]
Is there a way to get achieve this?

Docker SDK - Can't connect to DB from HOST

I want to create a temporary MySQL database for unit testing in Python. I decided to go with docker as the tests will be run on different machines.
As a first thing I run the container:
client = docker.from_env()
container = client.containers.run("ubuntu/mysql", detach=True, ports={3306:3307},environment={
'MYSQL_USER':'mysqluser',
'MYSQL_PASSWORD':'password',
'MYSQL_DATABASE':'mydb',
})
print('Container Started : {}'.format(container.status))
And then I try to connect using SQLAlchemy:
engine = sa.create_engine(f'mysql+pymysql://mysqluser:password#localhost:3307/mydb')
engine.connect()
which returns:
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
EDIT
After putting sleep(10) after container.run, the response is different:
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
Do you know what I'm doing wrong?
What I want to do is to connect to MySQL database on port 3307 (as one server already runs on the host). Then I want to create and populate a table.
EDIT2
Switching ports to {3307:3306} returns error:
docker.errors.APIError: 500 Server Error for http+docker://localhost/v1.41/containers/67a04b384bf3d39407881d4dfc73961932a3ce72fe8dc82c3cd6aedd57da2821/start: Internal Server Error ("driver failed programming external connectivity on endpoint hopeful_leakey (97840eb42d2c09b5e9754b634481d8e048c57ba2de8ffc10b34261de2f76600b): Error starting userland proxy: listen tcp4 0.0.0.0:3306: bind: address already in use")

Python ODBC Connect to SQL Server with Service Account (trusted_connection=no)

I connect to my server no problem with SQL Alchemy or Pyodbc so long as I use a trusted connection:
pyodbc.connect("Driver={SQL Server};Server=myServer;Port=1433;Database=myDB;trusted_connection=yes")
sqlalchemy.create_engine('mssql://myServer/myDB?trusted_connection=yes&driver=SQL+Server')
But I need to connect with a service account with basic Windows Authentication. When I try to add the UID/PWD like so:
sqlalchemy.create_engine("mssql+pyodbc://myUserName:myPassWord#myServer?driver=SQL+Server?trusted_connection=no")
pyodbc.connect('DRIVER={SQL Server};SERVER=myServre;DATABASE=myDB;UID=myUserName;PWD=myPassword')
I get the error "Login failed for user 'myUserName'. (18456) (SQLDriverConnect); [28000] "
Bonus try:
sqlalchemy.create_engine("mssql+pyodbc://myUserName:myPassword#myDB?driver=SQL+Server?trusted_connection=no")
Returns '[Microsoft][ODBC Driver Manager] Data source name too long (0) (SQLDriverConnect)'
Using SQL Server 2018.
I've verified that the service account has all the right permissions on the DB I'm trying to connect to. FWIW, I've also tried connecting using my own Windows credentials instead of the service account's (but with trusted_connection=no) and I get the same error messages.
get the error "Login failed for user 'myUserName'. (18456) (SQLDriverConnect); [28000] "
None of the Microsoft ODBC drivers support using Windows Integrated Authentication (NTLM or Kerberos) using provided credentials. This connection string
DRIVER={SQL Server};SERVER=myServre;DATABASE=myDB;UID=myUserName;PWD=myPassword
is for SQL Auth, where you have a login and a database user created in SQL Server.
eg:
use mydb
create login myUserName with password='myPassword'
create user myUserName for login myUserName
grant select to myUserName
To use Windows Auth with this driver you have to run your program as the target user, do Windows-level impersonation, store a credential in the Windows Credential store, or use runas /netonly.

sqlalchemy, connect to a sqlexpress instance on a different port

I'm connecting successfully to my sqlexpress instance from sqlalchemy with the connection string:
connection_str = 'mssql+pyodbc://mylaptop\sqlexpress/master?driver=SQL+Server+Native+Client+11.0&trusted_connection=yes'
How would i connect to a sql instance on a non default port, is it possible?
connection_str = 'mssql+pyodbc://mylaptop\sqlexpress:1433/master?driver=SQL+Server+Native+Client+11.0&trusted_connection=yes'
is what i would expect the connection string to be but this returns the error:
(pyodbc.OperationalError) ('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]TCP Provider: No connection could be made because the target machine actively refused it.\r\n (10061) (SQLDriverConnect); [08001] [Microsoft][SQL Server Native Client 11.0]Login timeout expired (0); [08001] [Microsoft][SQL Server Native Client 11.0]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)
I've tried a number of combinations with the port but don't see a legal combination?
In a SQLAlchemy connection URI you can specify a SQL Server instance in one of two ways
server_name\instance_name, or
server_name:port
You should only be using one or the other. If you specify the instance_name then the port number is provided by the SQL Browser service on server_name. If you specify the port then the actual instance_name doesn't matter because the port number is already known.

pyodbc trusted connection not working on IIS

I'm building a Python web app on Flask that use pyodbc to read data from a SQL Server database. Only trusted connection is allowed per the database's policy.
When I tried on my local, it works perfectly well. But when I hosted it on IIS (via WFastCGI) it's not working (Internal Server Error is raised) - failed to connect on below:
pyodbc.connect(blabla,trusted_connection = yes)
Just want to know how the user can get their credential and then continue connection to the SQL.
This call has worked for me in the past (connecting to SQL Server):
conn = pyodbc.connect(''''
TRUSTED_CONNECTION=Yes;
DRIVER={SQL Server};
SERVER={myServer};
DATABASE=myDB;''')

Categories

Resources