connect to Azure SQL database via pyodbc - python

I use pyodbc to connect to my local SQL database which works withoout problems.
SQLSERVERLOCAL='Driver={SQL Server Native Client 11.0};Server=(localdb)\\v11.0;integrated security = true;DATABASE=eodba;'
cnxn = pyodbc.connect(SQLSERVERLOCAL) #works
I try the connection to the azure sql database with:
SQLSERVERAZURE='Driver={SQL Server Native Client 10.0};Server=tcp:mydatbase.database.windows.net,1433;Database=mydb;Uid=myuser#myerver;Pwd=mypass;Encrypt=yes;Connection Timeout=30;'
cnxn = pyodbc.connect(SQLSERVERAZURE) #works not
what gives me the error:
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

Besides the suggestions that provided by meet-bhagdev who recommended to use pymssql dirve that mentioned in link, to resolve the error: Data source name not found and no default driver specified (0) (SQLDriverConnect)') that encountered, please update your connect string as below to see if it works.
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=yoursqlAzureServer.database.windows.net,1433', user='yourName#yoursqlAzureServer', password='Password', database='DBName')

Download ODBC driver from Microsoft website and try installing it. I guess then the problem should disappear.
Here is the link:
https://www.microsoft.com/en-us/download/details.aspx?id=50420

Related

Trying to connect to IBMi Series DB2 database to use python to work with databases [duplicate]

im trying to make a connection to an as400 with db2 using pyodbc and the ibm db2 odbc driver.
import pyodbc
connection = pyodbc.connect(
driver='{IBM DB2 ODBC DRIVER}',
system='192.168.1.100',
uid='user',
pwd='pass')
c1 = connection.cursor()
#this is meaningless sql, i just want the connection
c1.execute('select * from libname.filename')
for row in c1:
print (row)
Running this gives me this error
python pydata.py
Traceback (most recent call last):
File "C:\Users\tca\Desktop\ScriptingSTuff\pydata.py", line 3, in <module>
connection = pyodbc.connect(
pyodbc.OperationalError: ('08001', '[08001] [IBM][CLI Driver] SQL1013N The database alias name or database name "" could not be found. SQLSTATE=42705\r\n (-1013) (SQLDriverConnect)')
Any ideas?
This is all under win10
EDIT:
Adding this "database='s10c38ft',"
import pyodbc
connection = pyodbc.connect(
driver='{IBM DB2 ODBC DRIVER}',
system='192.168.1.100,8471',
database='s10c38ft',
uid='user',
pwd='pass')
c1 = connection.cursor()
c1.execute('select * from libname.filename')
for row in c1:
print (row)
Makes it hang on a blinking cursor, I cant even CTRL+C to end it, I have to close cmd.
The proper driver name should be IBM i Access ODBC Driver (but see notes below). Other than that, your first example was correct:
connection = pyodbc.connect(
driver='{IBM i Access ODBC Driver}',
system='192.168.1.100',
uid='user',
pwd='pass')
If that doesn't work, there are two main possibilities:
You are using an old ODBC driver. This would happen if you are using the old iSeries Access (in which case the driver name is iSeries Access ODBC Driver) or even older Client Access (driver name Client Access ODBC Driver (32-bit)). If you choose the appropriate name for your driver, it will work.
You are using an ODBC driver that is not for IBM i. The most commonly used member of the Db2 family is Db2 for LUW (Linux, Unix, Windows), but there are others. None of these will work for you.
You can find out the list of exact ODBC driver names you have installed by calling pyodbc.drivers(). If you don't have any of the ones I mentioned above by name, then you don't have the right driver. The ODBC driver you want is the one described here.

PYODBC--Data source name not found. How to get valid connection String

I am using SQL Server with Docker. I am trying to connect with pyodbc to my server but then I've got:
pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
Using DBeaver I got some details:
SELECT
##servername AS 'Server Name',
##servicename AS 'Instance Name',
DB_NAME() AS 'Database Name',
HOST_NAME() AS 'Host Name'
and this SQL returns:
193aeb2132e4, MSSQLSERVER, model, HDZKNV2
How my connection string should looks like cause this one does not work (and I guess any variation of this)?
'DRIVER={Microsoft Access Text Driver};
SERVER=193aeb2132e4\MSSQLSERVER;
DATABASE=model;
Trusted_Connection=yes;
User=admin;
Password=passowrd'
Several issues:
MSSQLSERVER is the internal instance name for the default, unnamed instance of SQL Server - to connect to it, just use the server name (or IP address) without adding MSSQLSERVER as the instance name
You should not have Trusted_Connection=yes (use currently logged in user's credentials) along side with explicit username/password - use one or the other, but not both together.
And according to the official Microsoft documentation on PyODBC - you should use DRIVER={ODBC Driver 17 for SQL Server} and UID/PWD (not User)
So try these settings:
DRIVER={ODBC Driver 17 for SQL Server};
SERVER=193aeb2132e4;
DATABASE=model;
UID=admin;
PWD=passowrd

It says "The Teradata Server can't currently be reached over this network" when i'm trying to connect Teradata using Python

I have been trying to connect to teradata (on on-prem server) from linux ec2 machine programmatically using python. But program failing with an error.
Here are details i used:
environmental variables:
export ODBCINI=/opt/teradata/client/16.20/odbc_64/odbc.ini
export ODBCINST=/opt/teradata/client/16.20/odbc_64/odbcinst.ini
export LD_LIBRARY_PATH=/opt/teradata/client/16.20/odbc_64/lib
odbcinst.ini
[ODBC Drivers]
Teradata Database ODBC Driver 16.20=Installed
[Teradata Database ODBC Driver 16.20]
Description=Teradata Database ODBC Driver 16.20
Driver=/opt/teradata/client/16.20/odbc_64/lib/tdataodbc_sb64.so
# Note: Currently, Data Direct Driver Manager does not support Connection Pooling feature.
odbc.ini
[ODBC]
# For Data Direct to load its error messages
# Data Direct Driver Manager looks for the messages here:
# "/opt/teradata/client/16.20/locale/xx_xx/LC_MESSAGES/"
InstallDir=/opt/teradata/client/16.20/odbc_64
Trace=no
Pooling=yes
[ODBC Data Sources]
Teradata ODBC DSN=Teradata Database ODBC Driver 16.20
[Teradata ODBC DSN]
# This key is not necessary and is only to give a description of the data source.
Description=Teradata Database ODBC Driver 16.20
# Driver: The location where the ODBC driver is installed to.
Driver=/opt/teradata/client/16.20/odbc_64/lib/tdataodbc_sb64.so
# Required: These values can also be specified in the connection string.
DBCName=
UID=
PWD=
# Optional
AccountString=
CharacterSet=ASCII
DatasourceDNSEntries=
DateTimeFormat=AAA
DefaultDatabase=
DontUseHelpDatabase=0
DontUseTitles=1
EnableExtendedStmtInfo=1
EnableReadAhead=1
IgnoreODBCSearchPattern=0
LogErrorEvents=0
LoginTimeout=20
MaxRespSize=65536
MaxSingleLOBBytes=4000
MaxTotalLOBBytesPerRow=65536
MechanismName=
NoScan=0
PrintOption=N
retryOnEINTR=1
ReturnGeneratedKeys=N
SessionMode=System Default
SplOption=Y
TABLEQUALIFIER=0
TCPNoDelay=1
TdmstPortNumber=1025
UPTMode=Not set
USE2XAPPCUSTOMCATALOGMODE=0
UseDataEncryption=0
UseDateDataForTimeStampParams=0
USEINTEGRATEDSECURITY=0
UseSequentialRetrievalOnly=0
UseXViews=0
EnableUDFUpload=0
UDFUploadPath=Please enter the UDF folder path
Here is Python code for connecting to Teradata:
import teradata
udaExec=teradata.UdaExec(odbcLibPath="/opt/teradata/client/16.20/odbc_64/lib/libodbc.so",appName="testconnec", version="1.0",logConsole=False)
session = udaExec.connect(method="odbc", system="TeraDev",username="myusername", password="mypassword", driver="Teradata Database ODBC Driver 16.20");
Error after execution
teradata.api.DatabaseError: (439, u"[08001] [Teradata][WSock32 DLL] (439) WSA E HostUnreach: The Teradata server can't currently be reached over this network")
What am i missing here?
I was facing the same issue, I ran "pdestate -a" and result came "PDESTATE HARDSTOP/DOWN." meaning database services were not up and running. I typed " /etc/init.d/tpa start" and then "/etc/init.d/tgtw start" after that again "pdestate -a" and this time result was "PDESTATE RUN/STARTED."
Tldr; Start the database services before trying to connect to it via a script.

How can i connect to local advantage database using pyodbc in python?

As far as i can understand to use pyodbc you have to
cnxn = pyodbc.connect('DRIVER={Advantage ODBC Driver};SERVER=local;DataDirectory=\\AltaDemo\Demo\AltaPoint.add;DATABASE=AltaPoint;UID=admin;PWD=admin;ServerTypes=1;')
cursor = cnxn.cursor()
This is the error i get from the console when i run this
Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
The name of the driver is Advantage StreamlineSQL ODBC, so the bare minimum connect string is:
DRIVER={Advantage StreamlineSQL ODBC};DataDirectory=D:\Temp
Other optinal options are:
DefaultType=Advantage
User ID=xxx
Password=xxx
ServerTypes=2
AdvantageLocking=ON
CharSet=ANSI
Language=ANSI
Description=My ADS connection
Locking=Record
MaxTableCloseCache=25
MemoBlockSize=64
Rows=False
Compression=Internet
CommType=TCP_IP
TLSCertificate=
TLSCommonName=
TLSCiphers=
DDPassword=Dictionary Password
EncryptionType=
FIPS=False
TrimTrailingSpaces=True
SQLTimeout=600
RightsChecking=OFF
If you want to use the Local Server you have to pass ServerTypes=1 like you already have in your original string.
For more options and documentation see also:
The official documentation
ConnectionStrings.com

pyodbc.Error 'IM002' connecting to DB2

I downloaded Python 2.7 (python-2.7.1.amd64.msi) and pyodbc, the python extension module for connecting to DB2 database (i.e. pyodbc-2.1.8.win-amd64-py2.7.exe).
I wrote sample script as shown below.
import csv
import pyodbc
conn = pyodbc.connectpyodbc.connect('DRIVER={DB2};SERVER=localhost;DATABASE=DBT1;UID=scott;PWD=tiger;')
curs = conn.cursor()
curs.execute('select count(edokimp_id) from edokimp')
print curs.fetchall()
The script throws following error
pyodbc.Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnectW)')
As I am a newbie to Python, I realized from the error that I need to download the IBM DB2 driver for pyodbc and hence searched extensively on Google but couldn't find any.
I would greatly appreciate if you could point me to the site where I can download the driver and later explain me how to configure/load the driver.
In case of Java
the driver will be shipped in the form of ojdbc.jar which will be copied to the lib directory which will be on classpath
make changes to configuration file
reference the DataSource from Java Class
I am newbie to Python so I would greatly appreciate if you could let me know cooresponding steps with an example in Python.
You can get the PyDB2 driver on the project homepage.
If you run into compilation issues with the official Python, ActivePython is a good alternate distribution of Python on Windows.
Edit: If it asks you for DB2 headers, you need to get the IBM Data Server Client for ODBC and CLI.
It does work using pyodbc. I think you have a wrong connection string. After some research and tests I solved with this code:
con = pyodbc.connect('DRIVER=iSeries Access ODBC Driver;SYSTEM=10.0.0.1;UID=bubi;PWD=xyz;DBQ=DEFAULTSCHEMA;EXTCOLINFO=1')
cur = con.cursor()
cur.execute('select * from MYTABLE')
row = cur.fetchone()
if row:
field1 = row[0]
field2 = row[1]
# etc...
As you see it doesn't need a DSN to be configured on your system.
This connection string for pyodbc, work for me:
conexion_str = 'SYSTEM=%s;db2:DSN=%s;UID=%s;PWD=%s;DRIVER=%s;' % (self._SYSTEM, self._DSN, self._UID, self._PWD, self._DRIVER)
self._cnn = pyodbc.connect(conexion_str)

Categories