DEV Community

How to Talk to Any Database Using AI: Building a Text-to-SQL App

In today’s data-driven world, getting information out of a database usually requires knowing SQL. But what if you could just ask your database a question in plain English and get the answer instantly? Thanks to Large Language Models (LLMs) and Artificial Intelligence, this is no longer science fiction.

In this article, I will show you a real-world example of how to build a Text-to-SQL Query Generator using Python, Streamlit, and Hugging Face.

The Magic of Text-to-SQL
Text-to-SQL is a natural language processing (NLP) task where an AI model translates a human-readable question into a structured SQL query. This bridges the gap between non-technical users (like business analysts or managers) and complex databases.

Instead of writing:
SELECT Salary FROM employees WHERE Name = 'Bob';

A user can simply ask: "What is the salary of Bob?"

Building the App (Code Example)
To demonstrate this, I have created a lightweight web application. We will use Streamlit for the frontend, SQLite for a temporary local database, and the Hugging Face Inference API to access an open-source Text-to-SQL model (t5-base-finetuned-wikiSQL).

1. Setting up the Database
First, we create a temporary in-memory database using sqlite3 and populate it with some dummy employee data. (You can check the full source code in my GitHub repository linked below).

2. The Hugging Face Connection
We use a simple HTTP POST request to send our natural language question to the Hugging Face API. The model processes the text and returns the SQL equivalent.

API_URL = "https://api-inference.huggingface.co/models/mrm8488/t5-base-finetuned-wikiSQL"

def generate_sql(question):
    payload = {"inputs": f"translate English to SQL: {question}"}
    response = requests.post(API_URL, json=payload)
    return response.json()[0]['generated_text']
Enter fullscreen mode Exit fullscreen mode

3. The Streamlit Interface
With Streamlit, creating the UI takes just a few lines of code. We take the user's input, pass it to our generate_sql function, display the generated SQL on the screen, and then immediately execute that query against our SQLite database to show the results in a table!

Try it Yourself!
The integration of AI into database management is transforming how we interact with data, democratizing data access across entire organizations.

You can find the complete, runnable code in my public repository here: https://github.com/FabricioRams/Research-Team-Work-N-01-SQL-AI-Database-Solutions.git

Clone it, run pip install -r requirements.txt, and start talking to your database today!

Top comments (0)