I have Select access to a MS SQL database that I would like to extract data into a Pandas dataframe running inside a Jupyter notebook. For reasons out of my control, I have access to the database from a different user. How can I query the database from Jupyter while connected to my current user account?
Advertisement
Answer
This is how you can do this:
- Python needs to be installed for all users in computer.
- Install Visual C++ Build tools Microsoft C++ Build Tools – Visual Studio
- Create a directory for the virtualenv accesible by all users in the computer, for example:
mkdir C:virtualenv
- Make a copy of the Command Prompt and paste in the virtualenv directory.
From: C:UsersYOURUSERNAMEAppDataRoamingMicrosoftWindowsStart MenuProgramsSystem ToolsCommand Prompt
To: C:virtualenvCommand Prompt
- Run Command Prompt as different user (press shift + right click) and login with YOURDOMAIN.
username: YOURUSERNAME@YOURDOMAIN or YOURDOMAINYOURUSERNAME password: your password
cd C:virtualenv
- Create the virtualenv:
python -m venv .
- Connect to the virtualenv.
scriptsactivate
- Install dependencies
pip install --upgrade jupyter pyodbc sqlalchemy pandas pip
- Create a Jupyter configuration file for the user.
jupyter notebook --generate-config
- Close the Command Prompt.
- Right click on the Command Prompt shortcut, then select Properties.
- Clear and leave empty the values from Start in and replace the Target values with:
Target: %windir%system32runas.exe /user:YOURUSERNAME@YOURDOMAIN “CMD /k "cd C:virtualenv && Scriptsactivate && jupyter notebook”"
**Optional: You may add /savecred (after/user) and it will remember the password. For security reasons you should not do this. - Double click the command prompt to run Jupyter.
Create a notebook to connect to your SQL database and download a table into a Pandas dataframe.
JavaScript
x
27
27
1
import os
2
import pyodbc
3
import sqlalchemy as db
4
import pandas as pd
5
6
windomain = os.environ["userdomain"]
7
8
if windomain == "YOURDOMAIN":
9
server = "YOURSERVER"
10
database = "YOUDATABASE"
11
driver = "{SQL Server}"
12
connect = "DRIVER="+driver+";SERVER="+
13
server+";DATABASE="+database+
14
";Trusted_Connection=yes"
15
engine = db.create_engine(
16
"mssql+pyodbc:///?odbc_connect={}".format(connect))
17
else:
18
print("Open as different user.")
19
20
df = pd.read_sql(
21
"""
22
SELECT TOP(100) *
23
FROM [YOURDATABASE]
24
""",
25
con=engine,
26
)
27