I am trying to pull data from SQL server, I am able to pull the sample data ( up to top 1000 records) but when I run it for all records I get following error:
('01000', '[01000] [Microsoft][ODBC SQL Server
Driver][DBNETLIB]ConnectionWrite (send()). (10054) (SQLGetData);
[01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]General network
error. Check your network documentation. (11)')
I am using following syntax
import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
'Server=g8w00761s.inc.hpicorp.net;'
'Database=ContraDigital2.0;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
sql_query = pd.read_sql_query("""SELECT top 1000 * FROM [ContraDigital2.0].[dbo].[contra_anomaly_upfront_backend_1]""",conn)
print(sql_query)
Related
I'm trying to connect my SQL database with Python. I used:
import pyodbc
import pandas as pd
cnxn_str = ("Driver={SQL Server};"
"Server=server_name;"
"Database=database_name;"
"Trusted_Connection=yes;"
)
cnxn = pyodbc.connect(cnxn_str)
cursor = cnxn.cursor()
data = pd.read_sql("select * from dbo.table", cnxn)
But I get this error:
DatabaseError: Execution failed on sql Select ... : ('HY000', '[HY000] [Microsoft][ODBC SQL Server Driver]
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
How to connect python to SQL Server using pyodbc until now I wrote the below script but the system crash and display error:
I tried to connect the script to the localhost sql server and i had a successful connection but when I tried on the server on the same network it did crash
code:
import pyodbc
import pandas as pd
conn = pyodbc.connect(
ENGINE='sql_server.pyodbc',
driver='SQL Server',
NAME='testDB',
SERVER ='WIN-CMUH9TBNL53',
DSN='pythonDSN',
PORT='1433',
UID='test',
PWD="test",
)
cursor = conn.cursor()
sql_query=pd.read_sql_query('select * from testDB.dbo.t1',conn)
print(sql_query)
print(type(sql_query))
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); [08001] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)')
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.
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.