Connecting to Azure SQL with Python

安稳与你 提交于 2019-12-04 17:55:33

@Kyle Moffat, what OS are you on? Here is how you can use pyodbc on Linux and Windows: https://msdn.microsoft.com/en-us/library/mt763261(v=sql.1).aspx

Windows:

Linux:

  • Open terminal Install Microsoft ODBC Driver 13 for Linux For Ubuntu 15.04 +

     sudo su  
     wget https://gallery.technet.microsoft.com/ODBC-Driver-13-for-Ubuntu-b87369f0/file/154097/2/installodbc.sh  
     sh installodbc.sh  
    
  • For RedHat 6,7

    sudo su
    wget https://gallery.technet.microsoft.com/ODBC-Driver-13-for-SQL-8d067754/file/153653/4/install.sh 
    sh install.sh 
    
  • Install pyodbc

    sudo -H pip install pyodbc
    

Once you install the ODBC driver and pyodbc you can use this Python sample to connect to Azure SQL DB

import pyodbc 
server = 'tcp:myserver.database.windows.net' 
database = 'mydb' 
username = 'myusername' 
password = 'mypassword' 
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("SELECT @@version;") 
row = cursor.fetchone() 
while row: 
    print row[0] 
    row = cursor.fetchone()

If you are not able to install the ODBC Driver you can also try pymssql + FreeTDS

sudo apt-get install python
sudo apt-get --assume-yes install freetds-dev freetds-bin
sudo apt-get --assume-yes install python-dev python-pip
sudo pip install pymssql==2.1.1

Once you follow these steps, you can use the following code sample to connect: https://msdn.microsoft.com/en-us/library/mt715796(v=sql.1).aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!