pyodbc connecting to SQL Server 2012 problems - python

Below is the traceback. I've read all the other SO threads, googled for over two hours, and cannot figure this out. Here is what I have tried:
Both SQL Authentication and Windows Authentication versions of the connection string.
Using the SQL Server name (text) and also the IP Address of the server
Including and Excluding port 1443 (the default tcp/ip port for the SQL server)
Creating new rules in Windows Firewall to allow both inbound/outbound TCP at port 1443
List item
Traceback (most recent call last):
File "pythonscript.py", line 75, in
conn = pyodbc.connect(driver='{SQL Server}', server='ipaddress,1443', database='master', uid='XYZ\login', pwd='password')
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)'
here are some examples of what I've tried for the connection string:
conn = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = '1.1.1.1,1443', database = 'master')
then
conn = pyodbc.connect(driver='{SQL Server}', server='1.1.1.1,1443', database='master', uid='xyz\login', pwd='pwd'
then I also tried both of the above with the name of the server (text) rather than the IP address. I have no idea how to get this to work at this point.

Have you confirmed you have connectivity between the servers? Try telnet -
telnet serverName 1433
If that connects then you can focus on issues with Python or the connection string.
In your connection string change it to use the PORT parameter instead of the ,1433. Something like -
SERVER=1.1.1.1;PORT=1433;
I would also say you might be better off passing the whole string. Here is what I do on Linux using FreeTDS typically -
self.db_connection = pyodbc.connect("DRIVER=FreeTDS;SERVER=1.1.1.1;PORT=1433;DATABASE=myDB;UID=myUser;PWD=myPass;TDS_Version=8.0;")

CONNECTION FROM WINDOWS TO MS SQL SERVER DATABASE:
Here you have an example I use myself to connect to MS SQL database table with a Python script:
import pyodbc
server = 'ip_database_server'
database = 'database_name'
username = 'user_name'
password = 'user_password'
driver = '{SQL Server}' # Driver you need to connect to the database
port = '1433'
cnn = pyodbc.connect('DRIVER='+driver+';PORT=port;SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+
';PWD='+password)
cursor = cnn.cursor()
If you are trying to connect from a Windows device to the DB, go to ODBC Data Source Administrator from Windows, and check if you have installed the driver:
Where is the ODBC data source administrator in a Windows machine.
The image is in spanish, but you only have to click on 'Drivers' tab, and check if the driver is there as in the image.
CONNECTION FROM LINUX/UNIX TO MS SQL SERVER DATABASE:
If you are working in Linux/Unix, then you shoud install a ODBC manager like 'FreeTDS' and 'unixODBC'. To configure them, you have some examples in the following links:
Example: Connecting to Microsoft SQL Server from Linux/Unix
Example: Installing and Configuring ODBC

Related

Getting Login Failed error with sqlalchemy+PYODBC when trying to connect to mssql DB server with another Domain credentials,but connected with Pymssql [duplicate]

I am trying to use Python to connect to a SQL database by using Window authentication. I looked at some of the posts here (e.g., here), but the suggested methods didn't seem to work.
For example, I used the following code:
cnxn = pyodbc.connect(driver='{SQL Server Native Client 11.0}',
server='SERVERNAME',
database='DATABASENAME',
trusted_connection='yes')
But I got the following error:
Error: ('28000', "[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]
Login failed for user 'DOMAIN\\username'. (18456) (SQLDriverConnect); [28000] [Microsoft]
[SQL Server Native Client 11.0][SQL Server]Login failed for user 'DOMAIN\\username'.
(18456)")
(Note that I replaced the actual domain name and user name with DOMAIN and username respectively, in the error message above.)
I also tried using my UID and PWD, which led to the same error.
Lastly, I tried to change the service account by following the suggestion from the link above, but on my computer, there was no Log On tab when I went to the Properties of services.msc.
I wonder what I did wrong and how I can fix the problem.
Connecting from a Windows machine:
With Microsoft's ODBC drivers for SQL Server, Trusted_connection=yes tells the driver to use "Windows Authentication" and your script will attempt to log in to the SQL Server using the Windows credentials of the user running the script. UID and PWD cannot be used to supply alternative Windows credentials in the connection string, so if you need to connect as some other Windows user you will need to use Windows' RUNAS command to run the Python script as that other user..
If you want to use "SQL Server Authentication" with a specific SQL Server login specified by UID and PWD then use Trusted_connection=no.
Connecting from a non-Windows machine:
If you need to connect from a non-Windows machine and the SQL Server is configured to only use "Windows authentication" then Microsoft's ODBC drivers for SQL Server will require you to use Kerberos. Alternatively, you can use FreeTDS ODBC, specifying UID, PWD, and DOMAIN in the connection string, provided that the SQL Server instance is configured to support the older NTLM authentication protocol.
I tried everything and this is what eventually worked for me:
import pyodbc
driver= '{SQL Server Native Client 11.0}'
cnxn = pyodbc.connect(
Trusted_Connection='Yes',
Driver='{ODBC Driver 11 for SQL Server}',
Server='MyServer,1433',
Database='MyDB'
)
Try this cxn string:
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;PORT=1433;DATABASE=testdb;UID=me;PWD=pass')
http://mkleehammer.github.io/pyodbc/
I had similar issue while connecting to the default database (MSSQLSERVER). If you are connecting to the default database, please remove the
database='DATABASENAME',
line from the connection parameters section and retry.
Cheers,
Deepak
The first option works if your credentials have been stored using the command prompt. The other option is giving the credentials (UId, Psw) in the connection.
The following worked for me:
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=yourServer;DATABASE=yourDatabase;UID=yourUsername;PWD=yourPassword')
import pyodbc #For python3 MSSQL
cnxn = pyodbc.connect("Driver={SQL Server};" #For Connection
"Server=192.168.0.***;"
"PORT=1433;"
"Database=***********;"
"UID=****;"
"PWD=********;")
cursor = cnxn.cursor() #Cursor Establishment
cursor.execute('select site_id from tableName') #Execute Query
rs = cursor.fetchall()
print(rs)
A slightly different use case than the OP, but for those interested it is possible to connect to a MS SQL Server database using Windows Authentication for a different user account than the one logged in.
This can be achieved using the python jaydebeapi module with the JDBC JTDS driver. See my answer here for details.
Note that you may need to change the authentication mechanism. For example, my database is using ADP. So my connection looks like this
pyodbc.connect(
Trusted_Connection='No',
Authentication='ActiveDirectoryPassword',
UID=username,
PWD=password,
Driver=driver,
Server=server,
Database=database)
Read more here
Trusted_connection=no did not helped me. When i removed entire line and added UID, PWD parameter it worked. My takeaway from this is remove

Problem connecting to MySQL database using Python through ODBC

I'm having a problem establishing a connection to the MySQL database No matter what I try or change I seem to be getting the same error. I want to be able to use python to modify MySQL database using ODBC but being new to this I'm not sure how to go about it. This is the error message:
Traceback (most recent call last):
File "C:\Users\Lutho\PycharmProjects\pyODBC\main.py", line 17, in
conx = pyodbc.connect(f'''DRIVER={driver};
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [53]. (53) (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. (53)')
Code I used:
import pyodbc
# define the server and database name
driver = '{ODBC Driver 17 for SQL Server}'
server = 'Local instance MySQL80'
database = 'tarsdb'
username = 'root'
password = '1234'
# define connection string
conx = pyodbc.connect(f'''DRIVER={driver};
SERVER={server};
DATABASE={database};
Uid={username};
Pwd={password};''')
# create connection cursor
cursor = conx.cursor()
I also tried using Trusted_Connection=yes and moved my MySQL file into the same folder as my python file but nothing has worked. Is there something I'm missing that I don't know about? If you can solve my problem that would be much appreciated. (If the question looks messy, just know I had a problem formating it.)
The issue was trying to use the ODBC driver for Microsoft SQL Server when the target database was MySQL. ODBC drivers are not interchangeable between different database products.
Connecting to MySQL from Python is possible using pyodbc and "MySQL Connector/ODBC" but there are better alternatives, specifically mysqlclient or pymysql. Both are solid choices, although in many circumstances mysqlclient is significantly faster than pymysql.

Unable to set up SQL Server backend using pyodbc for airflow on a Centos 7 server

I'm trying to set up SQL Server backend for airflow. But getting this timeout error, when I do airflow initdb:
sqlalchemy.exc.OperationalError: (pyodbc.OperationalError) ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
My connection string in airflow.cfg looks like:
sql_alchemy_conn = mssql+pyodbc://user:password#xx.xx.xx.xx,1433/test_db?driver=ODBC+Driver+17+for+SQL+Server
I installed odbc drivers using:
https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15#microsoft-odbc-driver-13-for-sql-server
My odbcinst.ini file looks like:
[ODBC Driver 17 for SQL Server]
Description=Microsoft ODBC Driver 17 for SQL Server
Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.5.so.2.1
UsageCount=1
I went through these posts:
Pyodbc: Login Timeout Error
pyodbc.OperationalError: ('HYT00', u'[HYT00] [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
"Login timeout expired" error when accessing MS SQL db via sqlalchemy and pyodbc
Remote connection to MS SQL - Error using pyodbc vs success using SQL Server Management Studio
Most of these solutions are about: using SQL Server IP instead of instance name and appending port with IP. But, I'm trying to connect that way already.
When I'm trying to connect to sql server through python venv using:
import pyodbc
server = 'xx.xx.xx.xx'
database = 'test_db'
username = 'user'
password = 'password'
port = '1433'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';PORT='+port+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
Tried above connection string without port as well. Still getting the same time out error.
Any help regarding this would be appreciated. Thanks..
I'd look to your connection string.
For a start there's a typo in the example you've given a comma before defining your PORT variable.... but it looks like there's a different shape to connection strings based on your chosen SQL Server driver. And you look like you are using pymssql format rather than pyodbc despite using the ODBC driver.
From SQLALchemy docs https://docs.sqlalchemy.org/en/13/core/engines.html#microsoft-sql-server
# pyodbc
engine = create_engine('mssql+pyodbc://scott:tiger#mydsn')
# pymssql
engine = create_engine('mssql+pymssql://scott:tiger#hostname:port/dbname')
This problem got fixed by internal request, it was a firewall issue.

Connect to remote MSSQL 2016 using isql and python on Mac?

Goal: Connect to remote MSSQL 2016 server via Python.
Main approach: Closely followed tutorial in https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Mac-OSX .
Problem: Able to connect via tsql, but isql is not working. Errors
[S1000][unixODBC][FreeTDS][SQL Server]Unable to connect to data source
[37000][unixODBC][FreeTDS][SQL Server]Login failed for user 'DOMAIN\user-p'
[37000][unixODBC][FreeTDS][SQL Server]Cannot open database "TIT_BI_OPERATIONS" requested by the login. The login failed.
Things tried:
Different ODBC drivers 13.1, 17, FreeTDS
Inclusion/exclusion of escape character in the user name.
Host name vs host ip.
Settings:
odbc.ini
[ODS_DSN]
Description = Connection to ODS MS_SQL 2016
Driver = FreeTDS
Servername = ODS_DSN
Port = 40000
Database = TIT_BI_OPERATIONS
odbcinst.ini
[FreeTDS]
Driver=/usr/local/lib/libtdsodbc.so
Setup=/usr/local/lib/libtdsodbc.so
UsageCount=1
freetds.conf
[ODS_DSN]
host = 164.10.17.77
port = 40000
tds version = 7.4
client charset = UTF-8
Notes:
Even though, its not very promising to run python without connecting through tsql and isql first, i still tried without success. Using pyodbc, pypodbc, sqlalchemy.
Most errors in the form: Login failed for user 'DOMAIN\user-p'
For ODBC driver 13: Can't open lib '/usr/local/lib/libmsodbcsql.13.dylib'
I am able to connect via SQL PRO STUDIO, using exact same credentials.
If you have any thoughts which direction to go to climb out of this connection problem, it would be greatly appreciated. Thank you!
If you're using Windows domain auth, you'll have to use FreeTDS. Oddly enough, Windows domain auth isn't supported by the Microsoft ODBC Driver, only FreeTDS.
Since you can connect with the tsql command, that means FreeTDS is working. I'd recommend connecting directly from Python explicitly. Try a connection string like this:
import pyodbc
con = pyodbc.connect(
r"DRIVER={FreeTDS};"
r"SERVER=164.10.17.77;"
r"PORT=40000;"
r"DATABASE=TIT_BI_OPERATIONS;"
f"UID=DOMAIN\\user-p;"
f"PWD=yourpassword;"
r"TDS_Version=7.3;"
)
cursor = con.cursor();
cursor.execute("SELECT 'this' AS that")
for row in cursor.fetchall():
print(row)
Note that you do need two backslashes in the UID field to connect with Windows domain auth; that is not a typo!

Cannot establish connection to sql-server using pyodbc on Windows 7

I'm using ActivePython 2.7.2.5 on Windows 7.
While trying to connect to a sql-server database with the pyodbc module using the below code, I receive the subsequent Traceback. Any ideas on what I'm doing wrong?
CODE:
import pyodbc
driver = 'SQL Server'
server = '**server-name**'
db1 = 'CorpApps'
tcon = 'yes'
uname = 'jnichol3'
pword = '**my-password**'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes')
cursor = cnxn.cursor()
cursor.execute("select * from appaudit_q32013")
rows = cursor.fetchall()
for row in rows:
print row
TRACEBACK:
Traceback (most recent call last):
File "pyodbc_test.py", line 9, in <module>
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes')
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)')
You're using a connection string of 'DRIVER={SQL Server};SERVER=server;DATABASE=db1;UID=uname;PWD=pword;Trusted_Connection=yes', you're trying to connect to a server called server, a database called db1, etc. It doesn't use the variables you set before, they're not used.
It's possible to pass the connection string parameters as keyword arguments to the connect function, so you could use:
cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1,
trusted_connection=tcon, user=uname, password=pword)
I had the same error message and in my case the issue was the [SQL Server] drivers required TLS 1.0 which is disabled on my server. Changing to the newer version of the SNAC, SQL Server Native Client 11.0 fixed the problem.
So my connection string looks like:
cnxn = pyodbc.connect(driver='{SQL Server Native Client 11.0}',
host=server, database=db1, trusted_connection=tcon,
user=uname, password=pword)
I had faced this error due to another reason.
It was because my server had a "port" apart from the address.
I could fix that by assigning the following value to "Server" parameter of the connection string.
"...;Server=<server_name>,<port#>;..."
Note that it is a 'comma' and not 'colon'/'period'
cnxn = pyodbc.connect(driver='{SQL Server}', host=server, database=db1,
user=uname, password=pword)
print(cnxn)
I removed "Trusted_Connection" part and it worked for me.
Different security risks exist with either method. If you use Sql Server authentication you expose your userid/password in the code. But at least you process with the same credentials. If you use Windows authentication you have to insure all the possible users are setup with the right permission in the Sql server. With Sql authentication you can setup just one user but multiple people can use that one Sql User permissions wise.
I had the same issue today. I was using localhost in the connectionstring. Got rid of the issue by replacing localhost woth 'server name',. My db and application are running in the same machine.
If you don't have server name
go to Sql server management studio and execute below query, which will give you the server name.
SELECT ##SERVERNAME
The connection string look as below
conn = pyodbc.connect('Driver={SQL Server};'
'Server=myServerName;'
'Database=mydb;'
'Trusted_Connection=yes;')

Categories

Resources