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)") ```
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
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)")
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 ]