How to connect to Azure sql database through python anaconda jupyter - python

I am trying to connect to azure sql database through Jupyter notebook and later to load the data into excel/csv .I have the details of server and database only .Username & password i think by default its taking my desktop credentials(unsure).
Here is tried code
import pyodbc
cnxn = pyodbc.connect(Server=myserver;Database=mydatabase)

In order to connect to your Azure SQL database with your jupyter notebook use the following:
import pyodbc
server = 'tcp:SQLSERVER.database.windows.net' # Server example
database = '<INSERT DATABASE NAME>'
username = '<INSERT USERNAME>'
password = '<INSER PASSWORD>'
driver= '{ODBC Driver 17 for SQL Server}' # Driver example
connection= pyodbc.connect('DRIVER=' + driver + ';SERVER=' +server + ';PORT=1433;DATABASE=' + database +';UID=' + username + ';PWD=' + password)
cursor = connection.cursor() # Just something you can do
print(connection)
connection.close()
For more details you can refer to the following links:
Connect to Azure SQL Database using Python and Jupyter Notebook
Connect to Azure SQL Database in a Jupyter Notebook using Python
Quickstart: Use Python to query a database

You need to give username, password of the Azure SQL database in connextion. Below is the code to establish connection of Azure SQl database using python in Jupyter Notebook.
import pyodbc
# Establish the connection
server = 'xxxxx.database.windows.net'
database = 'xxx'
username = 'xxxx'
password = 'xxxx'
driver= '{ODBC Driver 17 for SQL Server}'
conn = pyodbc.connect('DRIVER=' + driver + ';SERVER=' +
server + ';PORT=1433;DATABASE=' + database +
';UID=' + username + ';PWD=' + password)
print(conn)
conn.close()
Reference: Use Python to query a database - Azure SQL Database & SQL Managed Instance | Microsoft Learn

Related

How to add my password to my pyodbc connection in python

I have the following code to connect to my SQL Server database. I am wondering where/how I can add my password so it automatically connects instead of asking for my password.
server = 'myserver'
database = 'mydatabase'
username ='johndoe#xyz.com'
Authentication='ADI'
driver= '{ODBC Driver 17 for SQL Server}'
conn = pyodbc.connect('DRIVER='+driver+
';SERVER='+server+
';PORT=1433;DATABASE='+database+
';UID='+username+
';AUTHENTICATION='+Authentication
)
I tried this but it did not work.
server = 'myserver'
database = 'mydatabase'
username ='johndoe#xyz.com'
Authentication='ADI'
driver= '{ODBC Driver 17 for SQL Server}'
conn = pyodbc.connect('DRIVER='+driver+
';SERVER='+server+
';PORT=1433;DATABASE='+database+
';UID='+username+
';AUTHENTICATION='+Authentication
';PWD= 'MyPassword'
)
Secondarily, is there another way to have it read my password without putting it in the code itself? If so, I would love any information on that.
I'm not 100% on pyodbc but this works for mysqldb & psycopg2.
If you are able to use the Environment Variables, you can store information in there and call it using os in your script. Once you have it stored, you can just change your code to something like this below:
import os
server = 'myserver'
database = 'mydatabase'
username ='johndoe#xyz.com'
Authentication='ADI'
driver= '{ODBC Driver 17 for SQL Server}'
conn = pyodbc.connect(DRIVER=driver,
SERVER=server,
PORT=1433,
DATABASE=database,
UID=username,
AUTHENTICATION=Authentication,
PWD= os.environ['MYPASSWORD']
)
This is what ended up working for me:
#def get_connection():
conn = pyodbc.connect(DRIVER= '{ODBC Driver 17 for SQL Server}',
SERVER='ServerName',
DATABASE = 'DatabaseName',
PORT=PortNumber,
Trusted_Connection = 'Yes',
UID = 'MyUserName',
PWD = 'MyPass',
Authentication = 'ActiveDirectoryPassword'
)

Connect the Azure SQL Server Database with Active Directory Password using python (Got error)

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.

Connecting to SQL Server named instance from Linux using pyodbc

I'm currently trying to connect to a SQL Server (that I don't have visibility into, but have credentials for) using PyODBC. The code that I have works on my Windows desktop, but does not work when moved onto my RedHat Linux machine. I need it on Linux in support of a project.
Here's what I have:
server = 'tcp:myserver\inst1'
database = 'mydatabase'
username = 'myusername'
password = 'mypassword'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + password)
And here is the error I'm getting:
pyodbc.OperationalError: ('HYT00', u'[HYT00] [unixODBC][Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
The one difference between the Windows version and Linux version is the driver portion. Windows uses '{SQL Server}' while the Linux version uses '{ODBC Driver 13 for SQL Server}'.
In my /etc/odbcinst.ini file, I have the following information:
[ODBC Driver 13 for SQL Server]
Description=Microsoft ODBC Driver 13 for SQL Server
Driver=/opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.1.so.9.1
UsageCount=1
Anyone have any suggestions?
Unlike the Windows versions of Microsoft's ODBC Drivers for SQL Server, the Linux versions of those drivers are unable to resolve SQL Server instance names. So on a Windows client we can use the following (provided that the SQL Browser service is running on the server)
cnxn = pyodbc.connect(
"Driver=ODBC Driver 17 for SQL Server;"
r"Server=myserver\SQLEXPRESS;"
# and so on
)
but that won't work on Linux. However we can use the sqlserverport module (which I maintain) to retrieve the port number from the SQL Browser service:
import pyodbc
import sqlserverport
servername = "myserver"
serverspec = f"{servername},{sqlserverport.lookup(servername, 'SQLEXPRESS')}"
conn = pyodbc.connect(
"Driver=ODBC Driver 17 for SQL Server;"
f"Server={serverspec};"
# and so on
Use the driver path instead of the driver name. In your example take the full /opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.1.so.9.1
use IP address and port number instead of name/instancename.
execute this query to have the real port number:
SELECT DISTINCT local_net_address, local_tcp_port FROM sys.dm_exec_connections
and then datasrc=N'192.168.1.112,61423'

How to pass connection parameter "ApplicationIntent=ReadOnly" when using pymssql

I only have readonly access to a SQL Server db. How do I pass connection parameter "ApplicationIntent=ReadOnly" when using pymssql to connect to the database? If pymssql doesn't support it, is there any other python library that I can use?
The only way to configure readonly connection intent with pymssql seems to be to configure freetds on which it's based, but it did not work out for me. I've had to use pyodbc instead of pymssql
from pyodbc import connect
conn = connect(
'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + host + ';PORT=' + port + ';DATABASE='
+ database + ';UID=' + user + ';PWD=' + password + ';ApplicationIntent=ReadOnly')
Because pymssql is dependent on FreeTDS
You really need to address the connection parameters to your MS-SQL server used by FreeTDS
Because ApplicationIntent is listed in the freetds user guide as an option you should be able to use it.
pyodbc has a readonly parameter. For example:
import pyodbc
conn = pyodbc.connect(driver='{SQL Server}', host=Server, database=Database,
trusted_connection='yes', user='', password='', readonly = True)

Remote connection to MS SQL - Error using pyodbc vs success using SQL Server Management Studio

I have a MS SQL database in the same network but in other computer.
Using the SQL Server Management Studio (SSMS) Express, I can find the database and connect without problems.
But when I use pyodbc to connect to the same server using:
import pyodbc
server = r"xxxER\xxxSQLSERV"
db = "xxxDB"
user = "xxx"
password = "xxxx"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server + ';DATABASE=' + db +';UID=' + user + ';PWD=' + password)
I get following error:
pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC SQL Server Driver]Login timeout expired (0) (SQLDriverConnect)')
OBS: I guess that the server string should be right, since if I change it I get always the following error:
pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (17) (SQLDriverConnect); [01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (53)')
Here the image showing success while using SQL Server Studio Express to connect remotely.
Try specifying the port:
import pyodbc
server = r"xxxER\xxxSQLSERV"
db = "xxxDB"
user = "xxx"
password = "xxxx"
port = "1433"
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server + ';PORT=' + port + ';DATABASE=' + db +';UID=' + user + ';PWD=' + password)
If you're still having issues, try using the IP or FQDN of the server.
"But why ...?"
For those interested in why SQL Server Management Studio (SSMS) can connect to servername\instance while other applications (like our pyodbc apps) cannot, it's because SSMS keeps an MRU (Most Recently Used) list of port numbers in the Windows registry at
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\SuperSocketNetLib\LastConnect
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSSQLServer\Client\SuperSocketNetLib\LastConnect
Each MRU entry (registry value) looks something like this:
Name: PANORAMA\SQLEXPRESS
Type: REG_SZ
Data: -1006030326:tcp:PANORAMA,52865
Once SSMS has successfully connected by instance name via the SQL Browser service on the remote machine, it can continue to connect by instance name even if the SQL Browser is no longer running on the remote machine, provided that the port number has not changed. Apps that don't use this MRU list (like our pyodbc app) need to have the SQL Browser service running on the remote machine every time they want to connect by instance name.
The most common scenario:
I want to connect to YOUR-PC\SQLEXPRESS. I try doing that from SSMS on MY-PC, but it doesn't work because the SQL Browser was installed with "Start Mode" set to "Manual" on YOUR-PC.
I ask you to start the SQL Browser service on YOUR-PC, and you kindly comply, but you just start the service and forget to change the "Start Mode" setting to "Automatic".
I am able to connect via SSMS (which caches the YOUR-PC\SQLEXPRESS port in the MRU). My python app can connect, too.
After the next time YOUR-PC restarts, I can connect via SSMS (via the MRU) but my python app cannot (because the SQL Browser service is no longer running on YOUR-PC).
Try changing the Driver from 'SQL Server' to 'SQL Server Native Client 11.0'.
I had the same error message and this fixed it for me.
I have this problem.I can connect with Management Studio (SSMS) but not work with pyodbc.
I add version odbc of sql and worked.
change your code to:
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server + ';DATABASE=' + db +';UID=' + user + ';PWD=' + password)
If not work change version 17 to 13 if not to 11 .
List versions of ODBC.

Categories