Skip to content

Instantly share code, notes, and snippets.

@NPS-ARCN-CAKN
Last active August 29, 2015 14:22
Show Gist options
  • Save NPS-ARCN-CAKN/bffadbb04f7d47803eec to your computer and use it in GitHub Desktop.
Save NPS-ARCN-CAKN/bffadbb04f7d47803eec to your computer and use it in GitHub Desktop.
Python: Connect to SQL Server database and execute queries
import pyodbc
connection = pyodbc.connect('DRIVER={SQL Server};SERVER=MYSQLSERVER\SERVERNAME;DATABASE=MyDatabase')
cursor = connection.cursor()
# select query example
cursor.execute("SELECT * FROM MyTable")
row = cursor.fetchone()
if row:
print row
# insert query example
sql = "INSERT INTO MyTable(a,b) VALUES('a','b')"
cursor.execute(sql)
cnxn.commit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment