Skip to content

Rahulgupta7777/Ask_Your_Db

Repository files navigation

Natural Language to SQL Generator

A specific and powerful Streamlit application that allows users to query their MySQL database using natural language. The application uses OpenAI's GPT models to translate English questions into optimized, safe, and schema-aware SQL queries.

Demo

Application Demo

Features

  • Natural Language Interface: Ask questions in plain English (e.g., "Show me the top 5 students by GPA").
  • Schema-Aware: Automatically fetches and understands your database structure (tables and columns).
  • Safe SQL Generation:
    • Read-only queries (SELECT) by default.
    • Strict safety rules against destructive commands (DROP, TRUNCATE) unless explicitly managed.
    • Sanitizes Markdown from LLM responses to prevent syntax errors.
  • Interactive Results: Displays query results in an interactive data table.
  • Transparent Execution: Shows the generated SQL before execution for verification.

Prerequisites

  • Python 3.8+
  • MySQL Database: A running MySQL instance (local or remote).
  • OpenAI API Key: Access to GPT-3.5/GPT-4 models.

Installation

  1. Clone the repository

    git clone <repository-url>
    cd nl-sql-generator
  2. Set up a Virtual Environment (Recommended)

    # macOS/Linux
    python3 -m venv venv
    source venv/bin/activate
    
    # Windows
    python -m venv venv
    .\venv\Scripts\activate
  3. Install Dependencies

    pip install -r requirements.txt
  4. Configuration Create a .env file in the root directory to store your API key securely:

    echo "GROK_API_KEY=sk-your-api-key-here" > .env

    (Make sure to add .env to your .gitignore)

Usage

  1. Start the Application

    streamlit run app.py
  2. Connect to Database

    • Provide your MySQL Host, User, Password, Database Name, and Port in the input fields.
    • Click Connect. The app will fetch the schema and prepare the system prompt.
  3. Ask Questions

    • Type your question in the text area (e.g., "Review all students in the Engineering department").
    • Click Generate & Run.
    • View the generated SQL and the resulting data.

Security Note

This tool executes SQL queries generated by an AI. While it includes safety prompts and basic sanitization, always review generated SQL before execution, especially on production databases. It is recommended to use a database user with read-only permissions (SELECT privileges) for this application to minimize risk.

About

Natural Language to SQL – Database Querying Platform

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors