I'm trying to fetch data from SQL database with pyodbc with the code given below.The connection works rarely, most of the time it gives the error,
OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC SQL Server
Driver]Login timeout expired (0) (SQLDriverConnect)')
import numpy as np
import pyodbc as odbc
conn_string = ('DRIVER={SQL Server};SERVER=test;DATABASE=DEV;UID=me;PWD=whatever;')
cnxn = odbc.connect(conn_string)
cursor = cnxn.cursor()
cursor.execute("Select * from PurchaseOrders")
rows = cursor.fetchall()
ID = [i[1] for i in rows]
ID_array = np.fromiter(ID, dtype= np.int32)
I have tried setting the timeout to zero and DRIVER={ODBC Driver 11 for SQL Server} as I'm using SQL Server 2014. None of these works.
There was a problem with DNS. I used the IP address of the server instead, works fine now.
Related
I am trying to connect to external MS SQL database server from our Linux server using pyodbc and I am getting error.
Code:
import pyodbc
server = 'XXXXXXXXX,port'
database = 'XXXXXXXXXXXXXXX'
username = 'XXXXXXXXXXXX'
password = 'XXXXXXXX'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
#Sample select query
cursor.execute("SELECT ##version;")
row = cursor.fetchone()
while row:
print(row[0])
row = cursor.fetchone()
cnxn.close()
Error:
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot open database "xxxxxxxxxx" requested by the login. The login failed. (4060) (SQLDriverConnect)')
I also tried reading multiple solutions and trying them for example:
putting password in brackets like --> password = '{XXXXXXXX}' becuase it had special characters.
Also tried giving server as --> server = 'tcp:XXXXXXXXX,port' nothing worked it all gives me same error.
Could you please guide me resolve this issue.
Many thanks for your help.
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
During connection (not query execution), following problem with timeout occurs:
('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
Code:
import pyodbc
import pandas as pd
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
DF = pd.read_sql_query(query, cnxn)
This problem doesn't exist on Windows. In both cases I am using Forticlient VPN. Other networking works fine. Current configuration: Ubuntu 20.04 current patch, Windows 10 current patch. Driver was installed with official Microsoft's instruction:
https://learn.microsoft.com/en-us/sql/connect/odbc/linux-mac/installing-the-microsoft-odbc-driver-for-sql-server?view=sql-server-ver15
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 ]
I am trying to switch a pyodbc connection to sqlalchemy.
The working pyodbc connection is:
import pyodbc
con = 'DRIVER={ODBC Driver 11 for SQL Server};SERVER=server.com\pro;DATABASE=DBase;Trusted_Connection=yes'
cnxn = pyodbc.connect(con)
cursor = cnxn.cursor()
query = "Select * from table"
cursor.execute(query)
I tried:
from sqlalchemy import create_engine
dns = 'mssql+pyodbc://server.com\pro/DBase?driver=SQL+Server'
engine = create_engine(dns)
engine.execute('Select * from table').fetchall()
Based on: http://docs.sqlalchemy.org/en/latest/core/engines.html
and: pandas.read_sql() is MUCH slower when using SQLAlchemy than pyodbc
(trying to setup a connection with Trusted_Connection = Yes)
But I receive the message:
OperationalError: (pyodbc.OperationalError) ('08001', '[08001]
[Microsoft][ODBC SQL Server Driver][DBNETLIB]No existe el servidor SQL
Server o se ha denegado el acceso al mismo. (17) (SQLDriverConnect);
[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen
(Connect()). (53)') (Background on this error at:
http://sqlalche.me/e/e3q8)
(Sorry for the spanish but it says that the SQL Server doesn't exist)
I am almost sure that it has to do with me not understanding the sintax for the engine connection. Could someone please explain me in detail how to convert the conection from pyodbc to sqlalchemy?
Thanks in advance!
PD: I am trying to implement sqlalchemy to use later in my code pandas.DataFrame.to_sql(engine)
I remember having similar issues getting sqlalchemy setup. I've attached my engine statement syntax. I don't remember the details, but I do remember the driver selection being a real pain point. I believe I had to download the ODBC 13 driver separately, but can confirm pd.read_sql() and df.to_sql are working like a charm now.
driver = 'ODBC+DRIVER+13+for+SQL+Server'
engine_stmt = ("mssql+pyodbc://%s:%s#%s/%s?driver=%s" % (username, password, server, database, driver )
engine = sqlalchemy.create_engine(engine_stmt)