I am trying to connect to azure sql database. But somehow I keep getting the following error:
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17
for SQL Server]Client unable to establish connection (0)
(SQLDriverConnect)')
I have ODBC Driver 17 installed.
here is my code:
import pyodbc
server = 'mftaccountinghost.database.windows.net'
database = 'mft_accounting'
username = 'localhost'
password = '######'
driver= '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("select * from dbo.expense_zoho")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
Here is my connection string on Azure SQL Database
Does anyone have an idea why the error pops up?
Thanks.
Please make sure you have created a SQL login with permission to connect to the database. You can try creating a contained database user as shown below and used that contained login to connect to the database. Have you created that login named localhost?
CREATE USER yourlogin WITH PASSWORD = 'Yh-EhGFjh+';
GO
exec sp_addRoleMember 'db_datareader', 'yourlogin';
GO
Make sure you have created a firewall rule as explained on this documentation and the server name and database names are correct (you have not misspelled them).
Try to connect using database tools like SSMS.
Make sure you have install the right Python SQL Driver.
Please reference this tutorial: Quickstart: Use Python to query an Azure SQL database.
Here's my example pyodbc code and it works well in my window.
import pyodbc
server = 'sqlserverleon.database.windows.net'
database = 'Mydatabase'
username ='ServerAdmin'
password = '****'
driver= '{ODBC Driver 17 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+
';SERVER='+server+
';PORT=1433;DATABASE='+database+
';UID='+username+
';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("SELECT * FROM TEST6")
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
Hope this helps.
Related
I am in a corporate environment. Using packages DBI and odbc I can easily establish a connection between R and a SQL database like that:
con <- DBI::dbConnect(
odbc::odbc(),
driver = SQL.driver,
server = SQL.server,
database = SQL.database,
encoding = SQL.encoding
)
I understood that, without specific UID/PWD, the Windows authentication is used by DBI.
Since this R code will have to run on an external server (in fact, it is a shiny application behind), I need to specify a UID/PWD, and for that I requested and get "service account" from my IT department.
However, as soon as I specify the service account UID/PWD to DBI::dbConnect() I get a login failure:
con <- DBI::dbConnect(
odbc::odbc()
,driver = SQL.driver
,server = SQL.server
,database = SQL.database
,encoding = SQL.encoding
,UID = SQL.UID
,PWD = SQL.PWD
)
# Error: nanodbc/nanodbc.cpp:1021: 28000: [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'xxxxxxxx'.
If I manually open MS SQL server and try to connect with this service account using the "SQL server authentication method" instead of "Windows authentication" I also have the same error.
According to the IT department, this is "normal" and I think I am supposed to launch MS SQL server using this service account as user, then to use the Windows authentication to connect. Funny thing is that we are not allowed to "run as" another user.
Therefore, assuming this mechanic would work, how one can mimic this behavior in R please?
I have a similar set up at work with personal creds and service acct creds to a MS SQLServer db. I use the following to connect with the service account...
Note that you will have to download the mssql jdbc jar file.
username <= "myusername"
password <- "mypassword"
drv <- RJDBC::JDBC("com.microsoft.sqlserver.jdbc.SQLServerDriver",
'mssql-jdbc-7.0.0.jre8.jar')
connection_string <- paste0("jdbc:sqlserver://10.10.10.01\\srv1;databaseName=dbname;user=",
username, ";password=", password, ";")
conn <- RJDBC::dbConnect(drv, connection_string)
I am trying to connect to an Azure SQL database using ODBC with an Azure Active Directory account with password authentication. I think the error is best shown as it's weird:
library(odbc)
con = dbConnect(odbc::odbc(),
driver = "SQL Server",
server = "myserver.database.windows.net",
database = "mydb",
uid = "myname#myazure.onmicrosoft.com",
pwd = "xxx")
This returns the following error:
Error: nanodbc/nanodbc.cpp:1021: HY000: [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open server "myazure.onmicrosoft.com" requested by the login. The login failed.
It appears ODBC is splitting my username (uid) on the # sign and using the right-most half as the server name (which is wrong of course), even though I've specified the server name as an argument. Has anyone ever come up against this strange behaviour? I'm not sure how to fix it.
Running into a odd error when trying to move a SQL connection details from R code to the DSN and using the DSN as the connection string.
Using the ODBC package, I can build a connection through RStudio using:
con <- DBI::dbConnect(odbc::odbc(),
Driver = "SQL Server Native Client 11.0",
Server = "XXX",
Database = "YYY",
uid = "username",
pwd = "password",
port = 1443)
This code above works correctly and allows the SQL connection. When moving this to the DSN (have attempted both user and system DSN) an error is generated. Both user and system DSN's have been tried and when connections are tested from the ODBC application in Windows (Win 10), the test is successful.
When using the code below in R, the connection fails.
con <- DBI::dbConnect(odbc::odbc(), "ZZZ")
Error: nanodbc/nanodbc.cpp:950: 28000: [Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed for user ''
This would seem to indicate that the username is unknown but my information is that all of the connection parameters are stored in the DSN entry. My initial setup was generated from:
https://support.rstudio.com/hc/en-us/articles/214510788-Setting-up-R-to-connect-to-SQL-Server-
Following the further discussion at the bottom of the page, only appears to discuss the code version of the connection.
https://db.rstudio.com/databases/microsoft-sql-server/
This link discusses the DSN component as well as ensuring the driver is available.
https://db.rstudio.com/getting-started/connect-to-database
This confirms the code structure when trying to use the DSN.
I also verified this code snippet via:
https://www.r-bloggers.com/setting-up-an-odbc-connection-with-ms-sql-server-on-windows/
I attempted to use the SQL Server Driver versus the Native Client version and received the same error except the ODBC SQL Server Driver identifier instead of the Native Client 11.0. This seems to indicate that the dbconnect call is at least identifying the DSN entry.
Using the code below I confirmed that the Driver for both SQL Server and native Client 11.0 were available.
sort(unique(odbcListDrivers()[[1]]))
Add trusted connection attribute
con <- DBI::dbConnect(odbc::odbc(),
Driver = "SQL Server Native Client 11.0",
Server = "XXX",
Database = "YYY",
Trusted_Connection = "True",
uid = "username",
pwd = "password",
port = 1443)
Not sure if you're encountering the same issue, but the credentials used during DSN creation (Windows account) were different from those used in the dbConnect function call (somehow, my Microsoft account).
The user in the error message did not exist in the Security roles within SQL Server, thus not granting access to connect to the database.
Granting the user in the error message access to the required SQL server/database fixed the issue*.
CREATE LOGIN [MicrosoftAccount\xyz#outlook.com] FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]
ALTER SERVER ROLE [sysadmin] ADD MEMBER [MicrosoftAccount\xyz#outlook.com]
* though additional security measures are advised in role creation, off-topic here.
This code works perfectly in R-Studio but there is no way to make it work in MS Management studio. It keeps on saying that:
[Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user 'myserver\LOCAL01'.
That is not my user give it is a trusted connection. Can someone help me understand it?
ALTER PROCEDURE [dbo].[TESTIM] AS
BEGIN
SET LANGUAGE ENGLISH
CHECKPOINTÂ
DBCCÂ DROPCLEANBUFFERS
EXEC sp_execute_external_script
#language = N'R'
, #script = N'
con <- "Server=myserver\\LOCAL;Database=mydb;Trusted_Connection=true";
sql <- RxInSqlServer(connectionString = con, shareDir = "c:\\TMP");
local <- RxLocalSeq(sql);
rxSetComputeContext(local)
ff <- RxSqlServerData(sqlQuery = "select top 1 * from mytable", connectionString = con);
t = rxImport(ff);
OutputDataSet <- data.frame(SUCCESS = TRUE);
'
WITH RESULT SETS (([SUCCESS] BIT))
END
So, when you execute sp_execute_external_script it executes under one of 20 Windows user accounts (worker accounts) that has been created during installation of SQL Server R Services. These accounts are created for the purpose of running tasks under a security token belonging to the SQL Server Trusted Launchpad service.
This works very well, but if you need to create a SQL connection inside your R script (as in your case) and you use trusted connection (Windows Authentication), you are executing under the user account mentioned above ('myserver\LOCAL01' in your case), and that account need to be given permission to log in to the SQL Server instance on your behalf.
To do this:
In SQL Server Management Studio, in Object Explorer, expand Security, right-click Logins, and select New Login.
In the Login - New dialog box, click Search.
Click Object Types and select Groups. Deselect everything else.
In Enter the object name to select, type SQLRUserGroup and click Check Names.
The name of the local group associated with the instance's Launchpad service should resolve to something like instancename\SQLRUserGroup. Click OK.
By default, the login is assigned to the public role and has permission to connect to the database engine.
Click OK.
That should do it (the above steps are copied from here.
If you want to read more about the user accounts you can have a look at my blog-post "Microsoft SQL Server R Services - Internals III".
Hope this helps!
Niels
I am trying to connect to Azure SQL Datawarehouse using RStudio. The only Authentication that is setup on the warehouse is Active Directory Password Authentication. I tried using the below connection string.
connectionString="Data Source = abc.database.secure.windows.net; Authentication=Active Directory Password;
Initial Catalog=dbo; UID='UserName';
PWD= ;
It fails with "neither DSN nor SERVER keywork supplied" . And I dont want to set up a DSN as I am building a front end app and it must be portable.
I tried RODBC too ..but couldn't get much help with Active Dir Authentication.
I finally got to the bottom of this after a few deadends. A key step is updating your ODBC driver to ODBC Driver 17. The following works using Azure Active Directory authentication, which is slightly different to a consumer key/consumer secret but may achieve the same outcome (i.e. authentication without a SQL password).
library(DBI)
server <- "yourserver.database.windows.net"
database = "database-name"
con <- DBI::dbConnect(odbc::odbc(),
UID = rstudioapi::askForPassword("username"),
Driver="ODBC Driver 17 for SQL Server",
Server = server, Database = database,
Authentication = "ActiveDirectoryInteractive")
For integrated AD authentication the connection string should look like:
Driver={ODBC Driver 13 for SQL Server};Server=tcp:{full qualified server name},1433;Database={dbname};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryIntegrated
For AD passoword authentication:
Driver={ODBC Driver 13 for SQL Server};Server=tcp:{full qualified server name},1433;Database={dbname};Uid={your_user_name};Pwd={your_password_here};Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;Authentication=ActiveDirectoryPassword
Did you download the ADALSQL.DLL library https://www.microsoft.com/en-us/download/details.aspx?id=48742? required to connect to Azure AD. Also to double check the ODBC driver you use is 13.1 - correct?
If the recommendation indicated above (the ADALSQL.dll download) will not solve your problem, please create a customer case for "Azure AD authentication with SQL DB" and report it to SQL customer service.
This code works but a window appears:
library(DBI)
server <- "xxxxxxxx.database.windows.net"
database = "myDB"
con <- DBI::dbConnect(odbc::odbc(),
UID = "name#mycompany.com",
Driver="ODBC Driver 17 for SQL Server",
Server = server, Database = database,
Authentication = "ActiveDirectoryInteractive")