Home › Interview Questions › You need to read data from a MySQL table, but you …

You need to read data from a MySQL table, but you cannot store the credentials in your notebook. How would you write code to handle this securely? Provide a code structure.

🟡 Medium Conceptual Junior level
1Times asked
Sep 2026Last seen
Sep 2026First seen

💡 Model Answer

Avoid hard‑coding credentials in the notebook. The most common approach is to keep them in environment variables or a secrets store and read them at runtime. For example, in a Jupyter notebook you can use python‑dotenv to load a .env file that is excluded from version control:

python
from dotenv import load_dotenv
import os
import mysql.connector

load_dotenv()  # loads .env into os.environ
host = os.getenv("DB_HOST")
user = os.getenv("DB_USER")
password = os.getenv("DB_PASSWORD")
db = os.getenv("DB_NAME")

conn = mysql.connector.connect(host=host, user=user, password=password, database=db)
cur = conn.cursor()
cur.execute("SELECT * FROM my_table")
rows = cur.fetchall()

If you are on AWS, you can fetch the secret from Secrets Manager:

python
import boto3, json
client = boto3.client('secretsmanager')
secret = client.get_secret_value(SecretId='mydbsecret')
creds = json.loads(secret['SecretString'])
conn = mysql.connector.connect(**creds)

Both patterns keep credentials out of the notebook and version control, allow rotation, and can be integrated with CI/CD pipelines. The runtime cost is negligible; the database query itself is O(n) in the number of rows returned. This solution is suitable for junior to mid‑level engineers and scales to production workloads.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500