Skip to content

Instantly share code, notes, and snippets.

@VankatPetr
Created April 13, 2019 12:52
Show Gist options
  • Save VankatPetr/5a2d6ea582b2072b6926dc3271e2c189 to your computer and use it in GitHub Desktop.
Save VankatPetr/5a2d6ea582b2072b6926dc3271e2c189 to your computer and use it in GitHub Desktop.
Dynamic SQL using Python
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"import pyodbc\n",
"import pandas as pd\n",
"import textwrap"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"#create connection to MS SQL server\n",
"conn = pyodbc.connect('Driver={SQL Server};'\n",
" 'Server=VAIO\\SQLEXPRESS;'\n",
" 'Database=AdventureWorks2014;'\n",
" 'Trusted_Connection=yes;')"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"#define a dynamic component for the SQL query\n",
"code='98011'"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"#compose SQL query\n",
"sql_query_string = textwrap.dedent(\n",
" f\"\"\"\n",
" SELECT * \n",
" FROM Person.Address\n",
" WHERE PostalCode='{code}'\n",
" \"\"\"\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"#run SQL query and create DataaFrame\n",
"df = pd.read_sql(sql_query_string, conn)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment