Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)')
like image 822
nicholsonjf Avatar asked Sep 17 '13 21:09

nicholsonjf


People also ask

Can not establish a connection with the SQL Server?

Check to see if allow remote connections for this server is enabled. In SSMS, right click on the instance name and select Properties. Go to the Connections tab and make sure Allow remote connections to this server is checked. If you need to make a change, you must restart the SQL Server instance to apply the change.

What is the alternative to Pyodbc?

Top Alternatives to pyodbcThe AWS SDK for Python. Pytest: simple powerful testing with Python. Python wrapper for the Cloudflare v4 API. Powerful data structures for data analysis, time series, and statistics.


1 Answers

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)
like image 62
mata Avatar answered Oct 04 '22 07:10

mata