File size: 1,770 Bytes
8e2c076
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7b0d1f
 
 
 
 
 
 
 
 
8e2c076
 
 
 
 
 
 
 
 
 
 
 
 
b7b0d1f
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
51
52
53
54
55
56
57
58
59
60
61
62
import gradio as gr
import pandas as pd
from pandasql import sqldf

# 模拟数据库表
products = pd.DataFrame({
    "product_id": [1, 2, 3, 4, 5],
    "name": ["iPhone 14", "Galaxy S22", "Sony WH-1000XM5", "MacBook Pro", "Echo Dot"],
    "category": ["Electronics", "Electronics", "Audio", "Computers", "Smart Home"],
    "price": [799.99, 699.99, 399.99, 1999.99, 49.99],
    "stock": [50, 40, 30, 20, 70]
})

orders = pd.DataFrame({
    "order_id": [1, 2, 3],
    "order_number": ["ORD001", "ORD002", "ORD003"],
    "customer_id": [1, 2, 3],
    "total_amount": [1599.98, 699.99, 399.99],
    "status": ["PAID", "PAID", "PENDING"]
})

customers = pd.DataFrame({
    "customer_id": [1, 2, 3],
    "name": ["Alice", "Bob", "Charlie"],
    "email": ["alice@example.com", "bob@example.com", "charlie@example.com"],
    "phone": ["1234567890", "2345678901", "3456789012"]
})

order_items = pd.DataFrame({
    "order_item_id": [1, 2, 3],
    "order_id": [1, 2, 3],
    "product_id": [1, 2, 3],
    "quantity": [2, 1, 1],
    "subtotal": [1599.98, 699.99, 399.99]
})

# 定义查询函数
def query_to_sql(sql_query):
    try:
        # 将 Pandas 数据帧作为 SQL 查询的上下文
        context = {
            "products": products,
            "orders": orders,
            "customers": customers,
            "order_items": order_items
        }
        result = sqldf(sql_query, context)
        return result.to_string(index=False)  # 返回查询结果
    except Exception as e:
        return f"Error: {str(e)}"

# 创建 Gradio 界面
interface = gr.Interface(
    fn=query_to_sql,
    inputs="text",
    outputs="text",
    title="SQL Query Simulator",
    description="输入 SQL 查询语句,模拟查询结果。"
)

# 启动应用
interface.launch()