Skip to content

Instantly share code, notes, and snippets.

@trigfa
Created March 9, 2017 14:32
Show Gist options
  • Save trigfa/7b045f498837ff84f9b529b750428699 to your computer and use it in GitHub Desktop.
Save trigfa/7b045f498837ff84f9b529b750428699 to your computer and use it in GitHub Desktop.
Connecting to an MS SQL database using pyodbc
import pyodbc
import pandas as pd
#DDefine our connection parameters
con = pyodbc.connect(   
r'DRIVER={SQL Server};'   
r'server=server_address;'   
r'database=database_name;'   
r'uid=user_name;'   
r'pwd=password'
)
#Establish the connection
cursor = con.cursor()
#Define an SQL query, The keyword TOP reads only the first ten items in the table
#(Handy for not knocking over the server when testing
sql = """SELECT TOP 10 DoctorId, FirstName, LastName
FROM Doctor
"""
# Read the data from our query into a pandas dataframe
df = pd.read_sql_query(sql, con)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment