Connecting to ODBC using pyODBC - python

I've read all the faq pages from the python odbc library as well as other examples and managed to connect to the DSN, using the following code:
cnxn = pyodbc.connect("DSN=DSNNAME")
cursor = cnxn.cursor()
cursor.tables()
rows = cursor.fetchall()
for row in rows:
print row.table_name
but for everything else I keep getting this error:
Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
I know that I can pull up my data using Microsoft Access by going through the following steps: Creating a new database, clicking the external data tab, Click More and select ODBC database, use the Link to the data source by creating a linked table, in the Select data source window choosing Machine Data source and select NAME2 which has a System type, press okay and choose the table acr.Table_one_hh, then select the fields in the table that I want to look at like City, State, Country, Region, etc. When I hover over the table name it shows the DSN name, Description, Trusted Connection = Yes, APP, Database name and the table name.
I've attempted two methods, first
cnxn = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=mycomputername;DATABASE=mydatabase;Trusted_Connection=yes;')
cursor = cnxn.cursor()
which gives an error:
Error: ('08001', '[08001] [Microsoft][SQL Server Native Client 10.0]Named Pipes Provider: Could not open a connection to SQL Server [2]. (2) (SQLDriverConnect); [HYT00] [Microsoft][SQL Server Native Client 10.0]Login timeout expired (0); [08001] [Microsoft][SQL Server Native Client 10.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. (2)')
I tried
cnxn = pyodbc.connect("DSN=DSNNAME, DATABASE=mydatabase")
cursor = cnxn.cursor()
cursor.execute("""SELECT 1 AS "test column1" from acr.Table_one_hh""")
cursor.tables()
rows = cursor.fetchall()
for row in rows:
print row.table_name
which gave an error
Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

I managed to solve my issue. My code did not really change.
cnxn = pyodbc.connect("DSN=BCTHEAT")
cursor = cnxn.cursor()
cursor.execute("select * from acr.Table_one_hh")
row = cursor.fetchall()
then I wrote the results into a csv file.

Related

python connect to microsoft sql server db

I am trying to access a microsoft sql server DB trough python but I am receiving Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified')
The only info that I have is the db ip, user, password and db name. I used dbevear to set the connection and it's ok but I need to get data with python.
I tried the following:
import pypyodbc
import pandas as pd
cnxn = pypyodbc.connect(
"Server=171.11.111.11;"
"Database=database_name;"
"uid=my_username;pwd=secret")
df = pd.read_sql_query('select * from db.dtable', cnxn)
I am quite new to python and I don't exactly how to connect to the db. Am I missing something here?
This
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified'
means you failed to specify which ODBC driver you want to use. See eg
import pyodbc
# Some other example server values are
# server = 'localhost\sqlexpress' # for a named instance
# server = 'myserver,port' # to specify an alternate port
server = 'tcp:myserver.database.windows.net'
database = 'mydb'
username = 'myusername'
password = 'mypassword'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
Connecting to SQL Server using pyodbc

Connecting Python to Remote SQL Server

I am trying to connect Python to our remote SQL Server but I am not getting it. Following is a code that I used.
server = 'server,1433'
database = 'db'
username = 'username'
password = 'pw'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute('SELECT top 1 * FROM db.dbo.t_location')
for row in cursor:
print(row)
We have 2 servers. One is database server but I use application server for SQL which connects to database server. This is the error I'm getting. I am trying for a week but I'm not sure what am I missing here.
Any help would be appreciated
OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: No such host is known.\r\n (11001) (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. (11001)')
ADDED:
connection_str = ("Driver={SQL Server Native Client 11.0};"
"Server= 10.174.124.12,1433;"
#"Port= 1433;"
"Database=AAD;"
"UID=dom\user;"
"PWD=password;"
)
connection = pyodbc.connect(connection_str)
data = pd.read_sql("select top 1 * from dbo.t_location with (nolock);",connection)
I used the above code and now I see this error. Seems like it worked but failed to login. Usually I have to use Windows authentication in SSMS once I put my credentials to login in remote desktop.
('28000', "[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'dom\user'. (18456) (SQLDriverConnect); [28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'dom\user'. (18456)")
Answer:
I am excited that I finally found a solution using pymssql. I don't know pyodbc wasn't working but I am sure I must have had done something wrong. I used below code to get the data from remote SQL server using Python.
import pymssql
conn = pymssql.connect(
host=r'10.174.124.12',
user=r'dom\user',
password=r'password',
database='db'
)
cursor = conn.cursor(as_dict=True)
cursor.execute('Select top 4 location_id, description from t_location with (nolock)')
data = cursor.fetchall()
data_df = pd.DataFrame(data)
cursor.close()
Ignore my code at this moment. I still have to do some cleaning but this code will work.
Finally to answer my question, I had to use pymssql which worked. I did not have to put the port number which was making me confused. Thanks everyone for taking out time to answer.
import pymssql
conn = pymssql.connect(
host=r'10.174.124.12',
user=r'dom\user',
password=r'password',
database='db'
)
cursor = conn.cursor(as_dict=True)
cursor.execute('Select top 4 location_id, description from t_location with (nolock)')
data = cursor.fetchall()
data_df = pd.DataFrame(data)
cursor.close()
you can use this function :
def connectSqlServer(Server , Database , Port , User , Password):
try:
conn = pyodbc.connect('Driver={SQL Server}; Server='+Server+';
Database='+Database+'; Port='+Port+'; UID='+User+'; PWD='+Password+';')
cursor = conn.cursor()
except Exception as e:
print("An error occurred when connecting to DB, error details: {}".format(e))
return False, None
else:
return True, cursor

Connecting to Azure SQL Server via Jupyter (issues!)

I'm trying to connect to an Azure SQL Server instance from a laptop with Jupyter installed. Fairly new at this but having issues which are probably simple to resolve.
I've installed 64bit Python 3.7, Jupyter and AMD64 v17 pyodbc via pip. However when I'm trying to connect via Jupyter I just get either connection or driver issues, not quite sure.
Below is the code I'm trying to run to connect and return a simple top 10 rows query.
import pyodbc
server = 'xxxsqlserver.database.windows.net'
database = 'xxx.dbo.table'
username = 'user'
password = 'password'
driver='{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("SELECT TOP 10 * FROM xxx.dbo.table")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
Below is the error message I get:
InterfaceError Traceback (most recent call
last) in
5 password = 'password'
6 driver='{ODBC Driver 17 for SQL Server}'
----> 7 cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+
password)
8 cursor = cnxn.cursor()
9 cursor.execute("SELECT TOP 10 * FROM xxx.dbo.table")
InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager]
Data source name not found and no default driver specified (0)
(SQLDriverConnect)')
If I change the driver to 13 I get a different error
InterfaceError: ('28000', '[28000] [Microsoft][ODBC Driver 13 for SQL
Server][SQL Server]Login failed for user \'user\'. (18456)
(SQLDriverConnect); [28000] [Microsoft][ODBC Driver 13 for SQL
Server][SQL Server]Cannot open database "xxx.dbo.table" requested by
the login. The login failed. (4060); [28000] [Microsoft][ODBC Driver
13 for SQL Server]Invalid connection string attribute (0); [28000]
[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for
user \'user\'. (18456); [28000] [Microsoft][ODBC Driver 13 for SQL
Server][SQL Server]Cannot open database "xxx.dbo.table" requested by
the login. The login failed. (4060); [28000] [Microsoft][ODBC Driver
13 for SQL Server]Invalid connection string attribute (0)')
Feels like the driver isn't doing something quite right or I've got a misalignment somewhere. Note I didn't install any version 13 drivers but do have SSMS installed which put some in, and this connects to the Azure platform just fine.
Any ideas?
Thanks.
Hi there from the looks of things, this may be because your ODBC drivers are not installed properly. It is mostly likely because your are not formatting the string properly. So, here is a comprehensive list of what you need to do:
Install the correct ODBC drivers to connect with SQLServer
This depends on your operating system of course, if you have MacOS, you can go ahead and install it using homebrew like so:
brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
brew install msodbcsql17 mssql-tools
If you do not know what homebrew is, please take a look at the homebrew official website. If this is not your operating system, then take a look at OS specific instructions in this guide.
Once you have done this, make sure to follow the instructions at the end of the installation, where they tell you what changes you need to make to your dotfiles in order to get ODBC working properly.
Make sure to get the connection string properly. The connection string is located in the "Connection Strings" section of your SQLServer database, and under ODBC:
Once you have the connection string, use fstrings or the .format() function on a string to replace the section of the string that says Pwd={your_password_here}
This should do the trick. However, if it does not then you need to check whether you have the correct username, password and table. If you are sure that they are correct, then you might want to contact Support, since they might have changed the requirements for drivers to be a specific version for your database.
I've also encountered the same error while connecting to Azure SQL database.
The error disappeared once the driver name was changed from DRIVER={ODBC Driver 17 for SQL Server} to DRIVER={SQL Server}, for example:
import pyodbc
server = '<sql-server-name>.database.windows.net'
database = '<database>'
username = '<username>'
password = '<password>'
driver='{SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("SELECT TOP 10 * FROM dbo.allOrders")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()

unable to connect MSSQL using pyodbc

I have already looked up a lot of some what similar questions on StackOverflow regarding the connectivity of MSSQL with pyodbc, but none of their solutions helped.
I'm tring to connect a MSSQL database which is lying on a VM server, and I'm trying to access it from my local system. Following is the code:
import pyodbc
server = '172.xxx.xxx.xxx,1443'
database = 'sample_db'
username = 'SA'
password = 'xxxxx'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password+';Trusted_Connection=yes')
cursor = cnxn.cursor()
cursor.execute("SELECT name FROM sys.databases;")
results = cursor.fetchall()
print(results)
The error I'm getting is as follows:
pyodbc.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
If there's any other alternative to pyodbc that works better with MSSQL, please do mention that too.
Any help is appreciated, thanks.
Edit:
Upon #GordThompson suggestion I checked the driver in pyodbc.drivers() and found that my system only has 'SQL Server' driver so I changed the Driver to SQL Server. The present code looks like this:
import pyodbc
server = '172.xxx.xxx.xxx,1443'
database = 'sample_db'
username = 'SA'
password = 'xxxxx'
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password+';Trusted_Connection=yes')
cursor = cnxn.cursor()
cursor.execute("SELECT name FROM sys.databases;")
results = cursor.fetchall()
print(results)
But now i'm getting a totally different error, still not sure what it is
Error:
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)')
Its important to not mention the Trusted_Connection parameter when logging-in using UID and PWD. Hence, when I removed the Trusted_Connection parameter, it was able to establish the connection successfully.
So the connection string that later worked for me just had these,
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password)
cursor = cnxn.cursor()
[ Since #GordThompson didn't post it as an answer, I'm positing it here and closing it. Thanks #GordThompson ]

pyodbc.connect - works from one computer but not another

I have been running Python script using my desktop at work that successfully connects to a remote desktop server and outputs data in SQL via pyodbc.connect.
I am looking to migrate this code to a separate remote desktop PC recently installed at work and I get the following error:
InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
The code I am using is:
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=AUBAMTRAS01-DEV;"
"Database=ForwardTrading;"
"Username=xxxxxxxx;"
"Password=yyyyyyyy;"
"Trusted_Connection=yes;")
cursor = cnxn.cursor()
cursor.execute('SELECT distinct(Commodity) from ForwardCurvesOilAndGas')
for row in cursor:
print('row = %r' % (row,))
Data source name not found and no default driver specified
This means you need to install the SQLDriverConnect driver on your second machine.
SOLVED - Driver required was 'SQL Server' not 'SQL Server Native Client 11.0'

Categories