File size: 1,489 Bytes
b192407
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
SQL Template Module - Template for executing SQL queries in the environment.

This module provides a Python script template that:
- Connects to SQLite database files
- Executes SQL commands using pandas
- Outputs results to CSV files or prints directly

Reference: https://github.com/yiyihum/da-code/tree/main/da_agent/configs/sql_template.py
"""

SQL_TEMPLATE = """
import sqlite3
import pandas as pd
import os

def execute_sql(file_path, command, output_path):
    # make sure the file path is correct
    if not os.path.exists(file_path):
        print(f"ERROR: File not found: {{file_path}}")
        return

    # Connect to the SQLite database
    conn = sqlite3.connect(file_path)
    
    try:
        # Execute the SQL command and fetch the results
        df = pd.read_sql_query(command, conn)
        
        # Check if the output should be saved to a CSV file or printed directly
        if output_path.lower().endswith(".csv"):
            df.to_csv(output_path, index=False)
            print(f"Output saved to: {{output_path}}")
        else:
            print(df)
    except Exception as e:
        print(f"ERROR: {{e}}")
    finally:
        # Close the connection to the database
        conn.close()

# Example usage
file_path = "{file_path}"  # Path to your SQLite database file
command = "{code}"             # SQL command to be executed
output_path = "{output}" # Path to save the output as a CSV or "directly"

execute_sql(file_path, command, output_path)

"""