Skip to content

Instantly share code, notes, and snippets.

@leunardo
Created August 21, 2019 01:00
Show Gist options
  • Save leunardo/10dd7a6f8bd34a5c72970118a6a2ac08 to your computer and use it in GitHub Desktop.
Save leunardo/10dd7a6f8bd34a5c72970118a6a2ac08 to your computer and use it in GitHub Desktop.
Python pyodbc + pandas dataframe
# python 3.6+
import pandas as pd
from pyodbc import connect as connect_to_db
# database variables
sql_server = 'test'
database = 'test'
username = 'user'
password = 'password'
driver = '{ODBC Driver 17 for SQL Server}'
conn_string = f'DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password}'
columns = ['revenue', 'price', 'gas_leakage', 'id']
# stablish connection
with connect_to_db(conn_string) as conn:
query = pd.read_sql_query('select * from table', conn)
df = pd.Dataframe(query, columns=columns)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment