上一篇
场景引入:
凌晨3点,你盯着电脑屏幕上的Excel表格崩溃——10万行数据卡到闪退,公式计算转圈半小时,这时同事幽幽飘过:“为什么不用数据库?” 💡 别慌!今天手把手教你用Python操作MySQL,告别数据处理的“石器时代”!
确保你的电脑已安装:
打开终端/CMD,安装这两个神器:
pip install mysql-connector-python # MySQL官方驱动 pip install pandas # 可选,方便数据处理
import mysql.connector # 替换成你的数据库信息 config = { "host": "localhost", # 服务器地址 "user": "your_username", # 用户名 "password": "your_pwd", # 密码 "database": "test_db" # 数据库名 } try: conn = mysql.connector.connect(**config) print("✅ 连接成功!") except Exception as e: print(f"❌ 连接失败:{e}")
⚠️ 常见坑点:
Authentication plugin 'caching_sha2_password'
,在MySQL执行: ALTER USER '用户名'@'localhost' IDENTIFIED WITH mysql_native_password BY '密码';
# 创建游标 cursor = conn.cursor() # 示例1:查询数据 cursor.execute("SELECT * FROM employees WHERE salary > 5000") results = cursor.fetchall() # 获取全部结果 for row in results: print(f"员工:{row[1]},薪资:{row[3]}元 💰") # 示例2:插入数据 new_data = ("张三", "开发部", 8000) cursor.execute("INSERT INTO employees (name, department, salary) VALUES (%s, %s, %s)", new_data) conn.commit() # 重要!提交事务 print("📌 数据插入成功")
import pandas as pd # 将查询结果直接转为DataFrame df = pd.read_sql("SELECT * FROM products WHERE stock < 100", conn) print(f"库存预警商品:\n{df.head()}") # 导出到Excel df.to_excel("low_stock_products.xlsx", index=False) print("📤 导出完成!")
cursor.close() conn.close() print("🔌 连接已安全关闭")
🚨 忘记关闭的后果:数据库连接泄漏,最终导致服务崩溃!
with mysql.connector.connect(**config) as conn: with conn.cursor() as cursor: cursor.execute("UPDATE orders SET status='已完成' WHERE id=101") conn.commit() # 自动关闭连接,无需手动操作
# 防止SQL注入的正确方式 search_name = "O'Reilly" cursor.execute("SELECT * FROM books WHERE author=%s", (search_name,)) # 注意逗号!
data_list = [("A", 10), ("B", 20), ("C", 30)] cursor.executemany("INSERT INTO items (name, value) VALUES (%s, %s)", data_list) conn.commit()
✅ 核心流程:安装驱动 → 建立连接 → 执行SQL → 关闭连接
✅ 进阶技巧:Pandas整合、事务管理、防注入措施
✅ 避坑指南:记得commit()、用参数化查询、关闭连接
下次面对海量数据时,不妨试试这段代码:
import mysql.connector conn = mysql.connector.connect(host="localhost", user="root", database="your_data") print("🎉 欢迎来到数据库的世界!")
(本文方法基于mysql-connector-python 8.1.0版本验证,2025年8月测试通过)
本文由 运紫丝 于2025-08-03发表在【云服务器提供商】,文中图片由(运紫丝)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/529688.html
发表评论