diff --git a/README-EN.md b/README-EN.md index 17773c48..320640f9 100644 --- a/README-EN.md +++ b/README-EN.md @@ -228,13 +228,14 @@ $ python fuzzy.py /test_fuzzy foo bar ## Examples -| Name | File | -|---------------|------------------------------------------| -| Calculate | [calculate.py](./example/calculate.py) | -| Execute | [exec_code.py](./example/exec_code.py) | -| Request Route | [endpoint.py](./example/endpoint.py) | -| Image Search | [img_search.py](./example/img_search.py) | -| PIP | [pip.py](./example/pip.py) | +| Name | File | +|----------------|------------------------------------------| +| Calculate | [calculate.py](./example/calculate.py) | +| Execute | [exec_code.py](./example/exec_code.py) | +| Request Route | [endpoint.py](./example/endpoint.py) | +| Image Search | [img_search.py](./example/img_search.py) | +| PIP | [pip.py](./example/pip.py) | +| Database Query | [exec_sql.py](./example/exec_sql.py) | ## License diff --git a/README.md b/README.md index 2bac2d7e..2e8debd5 100644 --- a/README.md +++ b/README.md @@ -223,13 +223,14 @@ $ python fuzzy.py /test_fuzzy foo bar ## 示例 -| 名称 | 文件 | -|------|------------------------------------------| -| 计算 | [calculate.py](./example/calculate.py) | -| 执行代码 | [exec_code.py](./example/exec_code.py) | -| 请求路由 | [endpoint.py](./example/endpoint.py) | -| 图片搜索 | [img_search.py](./example/img_search.py) | -| PIP | [pip.py](./example/pip.py) | +| 名称 | 文件 | +|-------|------------------------------------------| +| 计算 | [calculate.py](./example/calculate.py) | +| 执行代码 | [exec_code.py](./example/exec_code.py) | +| 请求路由 | [endpoint.py](./example/endpoint.py) | +| 图片搜索 | [img_search.py](./example/img_search.py) | +| PIP | [pip.py](./example/pip.py) | +| 数据库查询 | [exec_sql.py](./example/exec_sql.py) | ## 许可 diff --git a/example/exec_sql.py b/example/exec_sql.py new file mode 100644 index 00000000..6f315a59 --- /dev/null +++ b/example/exec_sql.py @@ -0,0 +1,29 @@ +from sqlite3 import connect +from typing import Optional +from arclet.alconna import Alconna, Arg, Option, KeyWordVar, MultiVar + +db = connect('example.db') + +cursor = db.cursor() + + +select = Alconna( + "SELECT", + Arg("columns", MultiVar(str)), + Option("FROM", Arg("table", str, field="UNKNOWN")), + Option("WHERE", Arg("conditions", MultiVar(KeyWordVar(str)))), +) + + +@select.bind() +def exec_sql(columns: tuple[str, ...], table: str, conditions: Optional[dict[str, str]] = None): + if table == "UNKNOWN": + print("Table name is required.") + return + if conditions is None: + conditions = {} + cursor.execute(f"SELECT {', '.join(columns)} FROM {table} WHERE {' AND '.join(f'{k}={v}' for k, v in conditions.items())}") + print(cursor.fetchall()) + + +select.parse("SELECT health name FROM entertainment.pets WHERE USERID=MYID()") \ No newline at end of file