Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to accomplish query notification on SQL Server with python

I would like to set up a callback in Python when a table on SQL Server changes, similar to how its done for Oracle here.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/oow10/python_db/python_db.htm#t11

Is there a library that allows me to do so in Python, an example would be appreciated.

like image 439
Roman Avatar asked May 22 '13 13:05

Roman


People also ask

Can Python interact with SQL?

By default, your Python installation contains a Python SQL library named sqlite3 that you can use to interact with an SQLite database. What's more, SQLite databases are serverless and self-contained, since they read and write data to a file.

What is query notification in SQL Server?

Built upon the Service Broker infrastructure, query notifications allow applications to be notified when data has changed. This feature is particularly useful for applications that provide a cache of information from a database, such as a Web application, and need to be notified when the source data is changed.


1 Answers

First, download the ODBC Driver for Linux Then Install pyodbc using pip

pip install pyodbc==3.1.1

Create a py file with this code:

import pyodbc
server = 'yourserver.database.windows.net'
database = 'yourdatabase'
username = 'yourusername'
password = 'yourpassword'
driver= '{ODBC Driver 13 for SQL Server}'
cnxn = pyodbc.connect('DRIVER='+driver+';PORT=1433;SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("select @@VERSION")
row = cursor.fetchone()
if row:
    print row

That's your basic connection and call. Then follow the procedures from your oracle link, "Using Continuous Query Notification"

But... maybe b/c I am a SQL guy and a security wonk, it seems you'd be better off to have SQL Server push change notifications to somewhere python can get to it.

like image 80
Chris Beardsley Avatar answered Oct 30 '22 16:10

Chris Beardsley