Connecting Python to Remote SQL Server - python

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

Related

Cannot connect to MySQL database using SQLAlchemy

I have a Python program which is trying to connect to a MySQL 8.31 database. This is the code I am using.
connection_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=%s;UID=root;PWD=password" % db_name
connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string})
engine = create_engine(connection_url)
pd.read_sql('select * from apps_list', engine)
I get this exception
sqlalchemy.exc.OperationalError: (pyodbc.OperationalError) ('08001',
'[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes
Provider: Could not open a connection to SQL Server 1. (2)
(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. (2)') (Background on this error at:
https://sqlalche.me/e/14/e3q8)
I have researched this exception and most people recommend using SQL Server Configuration manager which I do not seem to have on my system.
Not in Computer Management
Not in C:\Windows\SysWOW64
Others have said to ensure Named Pipes are allowed which they are
And finally I've ensured Ports 3306 and 1433 are open
Yet I still get this exception.
For the record I am able to connect using this code
mydb = pymysql.connect(
host="localhost",
database=db_name,
user="root",
password="****",
autocommit=True
)
mycursor = mydb.cursor()
engine = create_engine('mysql+pymysql://****#localhost/%s' % db_name )
However this gives me a warning and tells me to use SQLAlchemy:
userwarning: pandas only support SQLAlchemy
connectable(engine/connection) ordatabase string URI or sqlite3 DBAPI2
connectionother DBAPI2 objects are not tested, please consider using
SQLAlchemy warnings.warn(
I am slightly confused at this because I am using SQLAlchemy to create the connection on this line
engine = create_engine('mysql+pymysql://****#localhost/%s' % db_name )
Is it fine the way I am currently connecting? Please let me know how I should connect.

How to resolve error when connecting to MS-SQL database via linux using pyodbc

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.

Timing out while trying to connect to sql in Azure Managed Instance from Azure VM

I am trying to access tables in SQL database in Azure Managed Instance (with IP: xxxx.database.windows.net) from a python script in Azure VM machine but I am getting the Operational Error below. I have tried with 2 different ways below.
Error:
OperationalError: ('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]TCP Provider: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.\r\n (10060) (SQLDriverConnect); [08001] [Microsoft][SQL Server Native Client 11.0]Login timeout expired (0); [08001] [Microsoft][SQL Server Native Client 11.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. (10060)')
1st way with connectionString:
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("mssql+pyodbc://<username>:<password>#<server>/<database>?driver=SQL+Server+Native+Client+11.0")
query = "select * from table"
df=pd.read_sql(query,engine)
2nd way with connectionString:
import pyodbc
server = 'xxx.database.windows.net'
database = 'database'
username = 'username'
password = 'password'
driver= '{SQL Server Native Client 11.0}'
with pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT TOP 3 name, collation_name FROM sys.databases")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
Besides, I have also tried to change the driver to drivers below, still no luck.
{ODBC Driver 11 for SQL Server}
{ODBC Driver 13 for SQL Server}
{ODBC Driver 17 for SQL Server}
{SQL Server Native Client 11.0}
Interesting part is, if I try the connect with the same connection string from on-premise machine which is not Azure VM (ex: my local machine or other servers I can RDP to), I can access the database. But when I try on a Azure VM machine, it is timing out. Do you have any ideas how to fix this problem?
Thank you for inputs.
So in the end we foud out that firewall caused this problem. We need to check firewall rules first.

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 ]

Connecting to ODBC using pyODBC

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.

Categories