Skip to main content

A Python package for seamless SQL Server database management, supporting secure connections, query execution, batch fetching, caching, and result exporting.

Project description

📌 PyDBManager - SQL Server Database Manager

Python SQL Server MIT License

Welcome to PyDBManager – a Python package for managing SQL Server connections and queries easily and efficiently! 🎯

This guide will help you:

  • ✅ Install PyDBManager
  • ✅ Set up your .env file for credentials
  • ✅ Perform SQL operations using Python
  • ✅ Save query results
  • ✅ Use caching & batch fetching

1. Install PyDBManager

Run the following command to install PyDBManager:

pip install pydbmanager

If installation is successful, continue to the next step!


2. Create .env File to Store Database Credentials

To avoid hardcoding credentials, create a .env file in your project directory.

Steps

  1. Create a .env file in your project root.
  2. Add the following credentials (update as needed):
    DB_SERVER=localhost
    DB_DATABASE=your_database_name
    DB_USERNAME=your_username
    DB_PASSWORD=your_password
    DB_DRIVER={ODBC Driver 17 for SQL Server}
    
  3. Ensure .env is ignored by Git (Add .env to .gitignore).
  4. Verify that .env loads correctly (Next step).

3. Verify .env File

Run this script to check if the values are loaded correctly:

import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

print("\u2705 Database Configuration Loaded:")
print(f"SERVER: {os.getenv('DB_SERVER')}")
print(f"DATABASE: {os.getenv('DB_DATABASE')}")
print(f"USERNAME: {os.getenv('DB_USERNAME')}")
print(f"PASSWORD: {'*' * len(os.getenv('DB_PASSWORD')) if os.getenv('DB_PASSWORD') else 'Not Set'}")
print(f"DRIVER: {os.getenv('DB_DRIVER')}")

Expected Output

Database Configuration Loaded:
SERVER: localhost
DATABASE: testDB
USERNAME: your_username
PASSWORD: **********
DRIVER: {ODBC Driver 17 for SQL Server}

4. Connect to the Database

from pydbmanager.connection import DatabaseConnection

# Initialize and test database connection
db = DatabaseConnection()
conn = db.create_connection()

if conn:
    print("\u2705 Connection Successful!")
    db.close_connection()
else:
    print("\u274c Connection Failed!")

Expected Output

Connection Successful!

5. Perform SQL Operations

🔹 Fetch All Users

from pydbmanager.operations import DatabaseOperations

db_ops = DatabaseOperations()

# Fetch all users
df = db_ops.query_data("SELECT * FROM users", batch_size=5)
df

Expected Output → A pandas DataFrame displaying user data.


🔹 Insert a New Record

insert_query = """
INSERT INTO users (name, email, age, gender, phone_number, address, city, country)
VALUES ('John Doe', 'john.doe@example.com', 29, 'Male', '123-456-7890', '123 Elm St', 'New York', 'USA')
"""
db_ops.execute_query(insert_query)
print("\u2705 User inserted successfully!")

🔹 Update a Record

update_query = """
UPDATE users SET age = 30 WHERE email = 'john.doe@example.com'
"""
db_ops.execute_query(update_query)
print("\u2705 User updated successfully!")

🔹 Delete a Record

delete_query = """
DELETE FROM users WHERE email = 'john.doe@example.com'
"""
db_ops.execute_query(delete_query)
print("\u2705 User deleted successfully!")

6. Saving Query Results

🔹 Save Data to CSV

db_ops.save_results(df, "users_data.csv", "csv")
print("\u2705 Data saved to users_data.csv")

📁 Check your project folder for users_data.csv


7. Using Caching & Batch Fetching

🔹 Query with Caching

df_cached = db_ops.cached_query("SELECT * FROM users")
df_cached

🔹 Query with Batch Fetching

df_batch = db_ops.query_data("SELECT * FROM users", batch_size= 10)
df_batch

🔹 Closing Connection

db_ops.close()
print("\u2705 Database connection closed.")

✅ Congratulations! 🎉

You’ve successfully used PyDBManager for:

  • Connecting to SQL Server
  • Running SQL queries in Python
  • Fetching, inserting, updating & deleting data
  • Using caching & batch fetching
  • Saving results to a file

🚀 Contributing & License

I welcome contributions! Feel free to submit issues and pull requests. 🛠️

This project is MIT Licensed — you are free to modify and distribute it as needed. 🏆

🔥 Happy Coding! 🚀

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydbmanager-0.1.1.tar.gz (7.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydbmanager-0.1.1-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file pydbmanager-0.1.1.tar.gz.

File metadata

  • Download URL: pydbmanager-0.1.1.tar.gz
  • Upload date:
  • Size: 7.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.16

File hashes

Hashes for pydbmanager-0.1.1.tar.gz
Algorithm Hash digest
SHA256 20aa1d7a7b65d59606909209a1aa530746bfa36d311c9c9daa6e8f5a55c44177
MD5 8f3cf0eb52004bad2c575469331cb132
BLAKE2b-256 85ec5fce64bcc05878052d70172addb90c025c87c282f0ed76af5c245e847966

See more details on using hashes here.

File details

Details for the file pydbmanager-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: pydbmanager-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 7.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.16

File hashes

Hashes for pydbmanager-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e678daaa12a15fecfb3eaf272d30f74417f09c4ee0112aa24877fcb24a32b837
MD5 45b9e1a4f90d3b6cdba9d5a585737260
BLAKE2b-256 b6d1b539d6c2af430117b5bf4f8580a10ecc61f4e93db8393076719c0ec507ed

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page