

大家好,这里是程序员晚枫,正在all in AI编程实战。
第23讲:AI数据库操作——让AI帮你写SQL
不用学SQL,用自然语言就能查数据库
很多人想查数据,但不会SQL。现在有了AI,你只需要说人话,AI帮你转成SQL。
1、准备工作
1
| pip install pymysql openai
|
2、连接数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import pymysql
conn = pymysql.connect( host="localhost", port=3306, user="root", password="你的密码", database="shop" )
cursor = conn.cursor() cursor.execute("SHOW TABLES") tables = cursor.fetchall() print("数据库表:", tables)
cursor.execute("DESCRIBE orders") columns = cursor.fetchall() for col in columns: print(col)
|
3、AI生成SQL
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
| from openai import OpenAI
client = OpenAI(api_key="你的Key", base_url="https://api.deepseek.com")
def describe_table(cursor, table_name): """获取表结构描述""" cursor.execute(f"DESCRIBE {table_name}") columns = cursor.fetchall() return "\n".join([f"{c[0]} ({c[1]})" for c in columns])
def text_to_sql(question): """自然语言转SQL""" cursor.execute("SHOW TABLES") tables = [t[0] for t in cursor.fetchall()] schema = [] for table in tables: schema.append(f"表名:{table}") schema.append(describe_table(cursor, table)) schema_text = "\n".join(schema) response = client.chat.completions.create( model="deepseek-chat", messages=[{ "role": "user", "content": f"""根据以下数据库表结构,生成SQL查询语句。只返回SQL,不要其他内容。
表结构: {schema_text}
查询需求:{question}""" }], temperature=0 ) return response.choices[0].message.content.strip()
|
4、执行AI生成的SQL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| def query_database(question): """自然语言查询数据库""" sql = text_to_sql(question) print(f"生成的SQL:{sql}\n") try: cursor.execute(sql) results = cursor.fetchall() return results except Exception as e: return f"SQL执行错误:{e}"
results = query_database("查询订单金额最高的前10个客户") for r in results: print(r)
|
5、数据分析与导出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| def analyze_data(question): """查询数据并让AI分析""" results = query_database(question) response = client.chat.completions.create( model="deepseek-chat", messages=[{ "role": "user", "content": f"分析以下查询结果,给出洞察:\n{results}" }] ) return response.choices[0].message.content
insight = analyze_data("各省份的月销售额") print(insight)
import pandas as pd df = pd.DataFrame(query_database(question)) df.to_excel("查询结果.xlsx", index=False)
|
6、实战:智能报表助手
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| def report_assistant(report_type): """生成各类报表""" queries = { "销售日报": "今天的销售总额和订单数", "客户分析": "购买次数最多的前10个客户", "库存预警": "库存低于100的商品", "月度汇总": "本月各品类的销售额" } if report_type in queries: result = query_database(queries[report_type]) analysis = analyze_data(queries[report_type]) report = f"# {report_type}\n\n## 数据\n{result}\n\n## AI分析\n{analysis}" office.word.create_word(report, f"{report_type}.docx") return report else: return "不支持的报表类型"
print(report_assistant("销售日报"))
|
下讲预告
学会了AI数据库操作,下一讲我们学 AI邮件处理——自动收发邮件。
敬请期待!
程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。
前3讲可以试听,试听链接:https://www.bilibili.com/cheese/play/ss982042944