[Django]-How to connect to Azure SQL database from Django app on Linux VM

7👍

✅

Here is a way to connect to your SQL Azure database in Python and Django using pymssql and FreeTDS on a Linux machine.
Here is how you can do it :
In the terminal, navigate to the directory where your manage.py is located.
Install the following packages:

sudo apt-get update  
sudo apt-get install freetds-dev freetds-bin
sudo apt-get install python-dev python-pip
sudo pip pymssql

You are essentially installing FreeTDS and Pymssql in your environment. This will allow you to connect to your SQL Database. What you are trying to do is use pyodbc natively with Django on a linux machine to access your SQL Azure database which is not possible currently.

Once you have the packages are installed you can use the following python code to create a table, insert/update a row and select all the contents. For simplicity/testing you can place the code in your views.py script. Make sure you have a database created in which you would like to create your table, otherwise it will select the default

# Connect
import pymssql
conn = pymssql.connect(server='test.database.windows.net', user='newuser@test', password='yourpassword', database='sampledatabase')
cursor = conn.cursor()

#Create
cursor.execute("""
IF OBJECT_ID('votes', 'U') IS NOT NULL
    DROP TABLE votes
CREATE TABLE votes (
    name VARCHAR(100),
    value INT NOT NULL,
    PRIMARY KEY(name)
)
""")

#Insert
cursor.executemany(
    "INSERT INTO votes VALUES (%s, %d)",
    [('NodeJS', '0'),
     ('Python', '0'),
     ('C#', '0')])
# you must call commit() to persist your data if you don't set autocommit to True
conn.commit()

        #Select
 cursor.execute('SELECT * FROM votes')
     result = ""
     row = cursor.fetchone()
     while row:
         result += str(row[0]) + str(" : ") + str(row[1]) + str(" votes")
         result += str("\n")
         row = cursor.fetchone()
     print result

We just created a table called votes, inserted values inside it and used a select statement to print all the contents. Hope this helps. If you still need help, don’t hesitate to reach out. I have a walk through guide that might help you if need be.

Leave a comment