当前位置: 首页 > news >正文

ollama - sqlcoder模型:面向提示词编程(根据用户信息生成sql语句并执行返回结果)

https://ollama.ac.cn/library/sqlcoder

https://blog.csdn.net/hzether/article/details/143816042

import ollama
import sqlite3
import json
from contextlib import closingdef generate_and_execute_sql(question: str, db_path: str) -> dict:# 1. 生成 SQL 查询语句prompt =  f"""### Instructions:Convert Chinese question to SQL query. Follow these rules strictly:1. ONLY return a valid SELECT SQL query2. Use EXACT table names from the mapping below3. DO NOT use any table that's not in the mapping### Examples:Question: 所有订单记录SQL: SELECT * FROM orders ORDER BY id;### Database Schema:{get_schema(db_path)}### Question:{question}### SQL Query:"""print(f"输入: {prompt}")response = ollama.chat(model='sqlcoder:latest',messages=[{'role': 'user', 'content': prompt}])sql_query = response['message']['content'].strip()print(f"生成的SQL: {sql_query}")  # 调试日志# 2. 执行 SQL 查询try:with closing(sqlite3.connect(db_path)) as conn:conn.row_factory = sqlite3.Row  # 设置为行工厂cursor = conn.cursor()cursor.execute(sql_query)# 3. 获取结果并转为 JSONrows = cursor.fetchall()result = [dict(row) for row in rows]return {"status": "success","sql": sql_query,"data": result}except Exception as e:return {"status": "error","sql": sql_query,"message": str(e)}def get_schema(db_path: str) -> str:"""获取数据库的 schema 信息"""with closing(sqlite3.connect(db_path)) as conn:cursor = conn.cursor()cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")tables = cursor.fetchall()schema_info = []for table in tables:table_name = table[0]cursor.execute(f"PRAGMA table_info({table_name});")columns = cursor.fetchall()col_details = [f"{col[1]} ({col[2]})" for col in columns]schema_info.append(f"表 {table_name}: {', '.join(col_details)}")return "\n".join(schema_info)# 使用示例
if __name__ == "__main__":# 配置参数DB_PATH = "data.db"  # SQLite 数据库文件路径QUESTION = "查询销售额超过10000的订单信息"  # 用户问题# 执行查询result = generate_and_execute_sql(QUESTION, DB_PATH)print(f"返回数据")print(json.dumps(result, indent=2, ensure_ascii=False))
D:\ProgramData\anaconda3\python.exe F:/mark/sqlauto/main.py
输入: ### Instructions:Convert Chinese question to SQL query. Follow these rules strictly:1. ONLY return a valid SELECT SQL query2. Use EXACT table names from the mapping below3. DO NOT use any table that's not in the mapping### Examples:Question: 所有订单记录SQL: SELECT * FROM orders ORDER BY id;### Database Schema:表 sqlite_sequence: name (), seq ()
表 orders: order_id (INTEGER), customer_name (TEXT), order_date (DATE), total_amount (REAL), status (TEXT)### Question:查询销售额超过10000的订单信息### SQL Query:生成的SQL: SELECT * FROM orders WHERE CAST(total_amount AS integer) > 10000;
返回数据
{"status": "success","sql": "SELECT * FROM orders WHERE CAST(total_amount AS integer) > 10000;","data": [{"order_id": 2,"customer_name": "李四","order_date": "2023-09-20","total_amount": 12000.5,"status": "shipped"},{"order_id": 4,"customer_name": "赵六","order_date": "2023-10-18","total_amount": 21000.0,"status": "delivered"},{"order_id": 6,"customer_name": "孙八","order_date": "2023-11-15","total_amount": 15500.0,"status": "delivered"},{"order_id": 8,"customer_name": "吴十","order_date": "2023-12-10","total_amount": 18900.75,"status": "delivered"}]
}Process finished with exit code 0

http://www.dtcms.com/a/275933.html

相关文章:

  • SQL新手入门详细教程和应用实例
  • 微信小程序121~130
  • [Vroom] 时间窗口 | 载重与货量管控 | 内部路由表示机制 | 增量式更新算法O(1)
  • 【Redis-05】高可用方案-主从哨兵
  • 【PTA数据结构 | C语言版】用两个栈实现队列
  • 监控28181连接到云服务器/推流分发/客户端网页端手机端拉流/实时性好极低延迟
  • 初等行变换会改变矩阵的什么?不变改变矩阵的什么?求什么时需要初等行变换?求什么时不能初等行变换?
  • GRPO PPO
  • Python 是动态类型的语言,它和静态类型语言(如 C++/Java)有什么优缺点?
  • CSS动画下划线
  • hot100链表(1)
  • 通过自制Flash算法文件,成功实现H7-TOOL脱机烧录nRF54L15,且支持自动解除SWD接口保护(2025-07-12)
  • Google MUVERA: 让多向量检索与单向量检索一样快
  • 2025Stockapi股票数据接口,股票实时数据,技术指标macd,kdj,cci技术指标算法,集合竞价数据,龙虎榜数据接口
  • TensorFlow2 study notes[2]
  • 启动Haproxy失败,如何排查问题
  • TCP与UDP协议详解:网络世界的可靠信使与高速快递
  • 参数化类型有哪些?自动化脚本如何实现数据参数化?
  • houdini vat 学习笔记
  • 滤波电路Multisim电路仿真实验汇总——硬件工程师笔记
  • Spring Security 安全认证深度解析与实战指南
  • 深入解析Java的G1收集器:原理、实战与优缺点
  • Pytest 跳过测试技巧:灵活控制哪些测试该跑、哪些该跳过
  • MCP调研及实践
  • JAVA线程池详解+学习笔记
  • 车载诊断架构 --- 诊断功能开发流程
  • 解决npm ERR! code ERR_SOCKET_TIMEOUT 问题
  • 光影证件照!支持一键换底和排版使用,内置多种模板,完全免费无广告
  • wedo稻草人-----第32节(免费分享图纸)
  • 数字孪生技术为UI前端注入新活力:实现产品设计的沉浸式体验