I'm trying to connect to SQL Server and run a query using the following code in Python:
import pyodbc
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server = server_name;"
"Database = database_name;"
"UID = user;"
"PWD = password;")
cursor = cnxn.cursor()
cursor.execute('SELECT TOP 10 [column] FROM [table]')
for row in cursor:
print('row = %r' % (row,))
I'm getting the following error:
Traceback (most recent call last):
File "filename", line 3, in <module>
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
pyodbc.Error: ('28000', "[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user 'username'. (18456) (SQLDriverConnect)")
("filename" and "username" inserted above as placeholders)
This is the same error, regardless of what I change the SQL Server username and password to in the code, and the user in the error is my windows login username.
I've also tried replacing UID and PWD with:
"Trusted_connection=yes"
... to no avail. I get the exact same error back.
I've tried several solutions for similar posts on Stackoverflow and elsewhere but no luck. Ideas to the problem or an alternative means of connecting to the database would be appreciated.
Thanks so much
Related
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
I am connecting to MSSQL Database. I am getting an error as the username contains "" I think this "" is giving the error.
In the following, I will attach my code and the error that I am getting. it would be good if someone can suggest some solution to this. As I already know there are two types of Authentication like Windows and the normal one. As I am trying to connect with the normal one. As I do have tried with the Windows one but it also didn't work out.
NOTE: I have tried with the commented connection string though but still not working. and you can see in the output that it is printing exactly what we want but when passing in the connect() function it's throwing an error.
Following is the code:
server = 'servername'
database = 'databasename'
username = dict_config['username'] #"LOCAL\shahrukhan"
print(username)
password = password_asdfsd
# conn_str = r'DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password
# print(conn_str)
# mssql_db_conn = pyodbc.connect(conn_str)
# mssql_db_conn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password)
# mssql_db_conn = pyodbc.connect(Trusted_Connection=True, driver = '{SQL Server}',server = server, database = database)
mssql_db_conn = pyodbc.connect('Driver={SQL Server};'
'Server=servername;'
'Database=databasename;'
'Trusted_Connection=yes;')
# mssql_db_conn = pyodbc.connect(Trusted_Connection='no',Driver='{ODBC Driver 17 for SQL Server}',Server=server,Database=database)
if(mssql_db_conn !=""):
mssql_db_cursor = mssql_db_conn.cursor()
print("Connected")
I am getting the following output:
LOCAL\\shahrukhan
DRIVER={ODBC Driver 17 for SQL Server};SERVER=servername;DATABASE=databasename;UID=LOCAL\\shahrukhan;PWD=password
Traceback (most recent call last):
File "test.py", line 34, in <module>
mssql_db_conn = pyodbc.connect(conn_str)
pyodbc.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'LOCAL\\shahrukhan'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'LOCAL\\shahrukhan'. (18456)") ```
I have Anaconda installed on one of our servers, and some code which successfully opens a connection to SQL (2016) on another server:
import pyodbc
conn_string = 'DRIVER={SQL Server Native Client 11.0};SERVER=wpic-smir;Trusted_Connection=yes'
conn = pyodbc.connect(conn_string)
cursor=conn.cursor()
qstring = 'select UserID from Diler_BW.Beckwith.V_Thermovals'
cursor.execute(qstring)
row=cursor.fetchone()
print row[0]
del cursor
del conn
Now, on the same server as Anaconda, we have SQL Server (2017) installed, and Machine Learning Service for Python is also installed. I'm trying to do run essentially the same code above, but from within SQL:
exec sp_execute_external_script
#LANGUAGE = N'Python',
#script = N'
import pyodbc
conn_string = ''DRIVER={SQL Server Native Client 11.0};SERVER=wpic-smir;Trusted_Connection=yes''
conn = pyodbc.connect(conn_string)
cursor=conn.cursor()
qstring = ''select UserID from Diler_BW.Beckwith.V_Thermovals''
cursor.execute(qstring)
row=cursor.fetchone()
print row[0]
del cursor
del conn
'
The code runs successfully from standalone Anaconda, but, from a SQL query connected to the 2017 server, it does not:
Msg 39004, Level 16, State 20, Line 0
A 'Python' script error occurred during execution of 'sp_execute_external_script' with HRESULT 0x80004004.
Msg 39019, Level 16, State 2, Line 0
An external script error occurred:
Error in execution. Check the output for more information.
Traceback (most recent call last):
File "<string>", line 5, in <module>
File "C:\ProgramData\MSSQLSERVER\Temp-PY\Appcontainer1\41EF254D-1B14-4D9D-99AF-8AD356A84BDC\sqlindb_0.py", line 39, in transform
conn = pyodbc.connect(conn_string)
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][SQL Server Native Client 11.0]Named Pipes Provider: Could not open a connection to SQL Server [65]. (65) (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. (65)')
Msg 39019, Level 16, State 2, Line 0
An external script error occurred:
SqlSatelliteCall error: Error in execution. Check the output for more information.
STDOUT message(s) from external script:
Express Edition will continue to be enforced.
SqlSatelliteCall function failed. Please see the console output for more information.
Traceback (most recent call last):
File "C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\revoscalepy\computecontext\RxInSqlServer.py", line 605, in rx_sql_satellite_call
rx_native_call("SqlSatelliteCall", params)
File "C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\PYTHON_SERVICES\lib\site-packages\revoscalepy\RxSerializable.py", line 375, in rx_native_call
ret = px_call(functionname, params)
RuntimeError: revoscalepy function failed.
The account I'm using for development is in the sysadmin role on both servers. We use Windows authentication only on both servers. I assume that something significant is different about the instance of python that SQL/MLS uses than the standalone installation.
Thank you.
I am trying to connect the Azure, SQL Server Database using Active Directory Password with python. But i got the below error.
Please check the below error:-
Traceback (most recent call last):
File "database_test.py", line 20, in <module>
main()
File "database_test.py", line 11, in main
connection = pyodbc.connect('DRIVER='+driver+';SERVER='+serverName+';PORT=1443;DATABASE='+dbName+';UID='+User_name+';PWD='+ password+';Authentication=ActiveDirectoryPassword')
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 13 for SQL Server]SQL Server Network Interfaces: The Microsoft Online Services Sign-In Assistant could not be found. Install it from http://go.microsoft.com/fwlink/?Link Id=234947. If it is already present, repair the installation. [2]. (2) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 13 for SQL Server]Client unable to establish connection (2); [08001] [Microsoft][ODBC Driver 13 for SQL Server]In
valid connection string attribute (0)')
Please Check the Below code:-
import pyodbc
def main():
serverName = "<ServerName>"
dbName = "<DatabaseName>"
User_name = '<UserName>'
password = '<Password>'
driver= '{ODBC Driver 13 for SQL Server}'
connection = pyodbc.connect('DRIVER='+driver+';SERVER='+serverName+';PORT=1443;DATABASE='+dbName+';UID='+User_name+';PWD='+password+';Authentication=ActiveDirectoryPassword')
cursor = connection.cursor()
data = cursor.execute("select * from dbo.test;")
allData = data.fetchall()
connection.close()
for i in allData:
print(i)
if __name__== "__main__":
main()
Is there any way to resolve the above problem?
Is it possible to connect azure sql server Database using pyodbc with Active Directory Password authentication? if possible what is the proper way to connect the Azure Sql Server Database with Active directory Password?
Please make you have installed the driver for Azure SQL database. You can download from this document Quickstart: Use Python to query an Azure SQL database.
This document can give more guides with Python.
And according you error message, you have missed "The Microsoft Online Services Sign-In Assistant". Please download and install it from the link provided for you:http://go.microsoft.com/fwlink/?Link Id=234947.
Here is my test Python code, I made some change that you can see more clearly:
import pyodbc
def main():
serverName = "****.database.windows.net"
dbName = "Mydatabase"
User_name = '****#****.com'
password = '****'
Authentication='ActiveDirectoryPassword'
driver= '{ODBC Driver 17 for SQL Server}'
connection = pyodbc.connect('DRIVER='+driver+
';Server='+serverName+
';PORT=1433;DATABASE='+dbName+
';UID='+User_name+
';PWD='+ password+
';Authentication='+Authentication)
cursor = connection.cursor()
data = cursor.execute("select * from dbo.tb1;")
allData = data.fetchall()
connection.close()
for i in allData:
print(i)
if __name__== "__main__":
main()
Note: I use ODBC Driver 17 for SQL Serve in my computer.
Hope this helps.
I am trying to connect to mssql using pyodbc in python and I am using MacOs Mojave. I write the code to make the connection but it gives me the Login failed for user, though I am pretty sure the user and password is correct.
import pyodbc
import getpass
server = "servername"
database = 'mydb'
username= 'username'
password = getpass.getpass("Enter your password: ")
conn = pyodbc.connect(Driver='{ODBC Driver 13 for SQL Server}',
Server=server,
Database=database,
UID=username,
pwd=password)
cursor = conn.cursor()
cursor.execute('SELECT TOP 100 * FROM my table')
for row in cursor:
print(row)
conn.close()
Traceback (most recent call last):
File "/Users/s3480912/Desktop/d2d_Xsell_Propensity/d2d-xsell-score-generator/score_generator.py", line 19, in <module>
pwd=password)
pyodbc.InterfaceError: ('28000', u"[28000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'username'. (18456) (SQLDriverConnect)")