AiAnyTool - Best AI Tools Directory and Artificial Intelligence Software Hub LogoAIAnyTool
Back to Agent Skills

SQL Database Query Executor

Custom / General Framework

Skill Description

Executes read-only SQL queries against a PostgreSQL, MySQL, or SQLite database. Includes safeguard checks to prevent destructive queries (UPDATE/DELETE).

Code / Definition File

skill_manifest.yaml / config.json
import os
import psycopg2

def execute_readonly_query(sql_query: str):
    """
    Executes a SELECT query securely.
    Returns rows as list of dicts.
    """
    # Security safeguard
    cleaned_query = sql_query.strip().lower()
    forbidden = ["insert", "update", "delete", "drop", "alter", "truncate"]
    if any(cmd in cleaned_query for cmd in forbidden):
        raise ValueError("Only SELECT queries are allowed for security reasons.")
        
    conn = psycopg2.connect(
        host=os.getenv("DB_HOST"),
        database=os.getenv("DB_NAME"),
        user=os.getenv("DB_USER"),
        password=os.getenv("DB_PASSWORD")
    )
    try:
        with conn.cursor() as cur:
            cur.execute(sql_query)
            colnames = [desc[0] for desc in cur.description]
            rows = cur.fetchall()
            return [dict(zip(colnames, row)) for row in rows]
    finally:
        conn.close()

Tags

sql database postgres read-only
Author: AiAnyTool
Added on: 6/7/2026