网站首页 > 文章精选 正文
今天展示python访问myql数据库的例子。网上查了一下有很多访问mysql用的python库,这里选用了mysql-connector-python库
安装mysql-connector-python库
执行pip install mysql-connector-python命令安装该库,如果出现类似这样的错误
pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.
就在这一个安装命令后面加一个镜像参数 -i
https://mirrors.aliyun.com/pypi/simple/
连接mysql DB
import mysql.connector
# 创建数据库连接
db = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
# 创建游标对象
cursor = db.cursor()
# 执行简单查询
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print("Database version:", data[0])
# 关闭连接
cursor.close()
db.close()
这段代码是Python操作MySQL数据库的基础示例,验证了连接是否成功并获取数据库版本信息。
连接参数:需要替换your_username、your_password和your_database为实际的数据库凭据
游标(cursor):是数据库操作的工作区,所有SQL操作都通过游标执行
fetchone():获取查询结果的下一行
资源释放:最后必须关闭游标和连接,这是良好的编程习惯
插入数据
先在mysql客户端执行建表语句
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
department VARCHAR(255),
salary DECIMAL(10, 2),
hire_date DATE
)
然后执行下面的代码
from datetime import date
……
# 插入单条数据
insert_sql = "INSERT INTO employees (name, department, salary, hire_date) VALUES (%s, %s, %s, %s)"
employee_data = ("John Doe", "IT", 75000.00, date(2020, 5, 15))
cursor.execute(insert_sql, employee_data)
# 插入多条数据
employees = [
("Jane Smith", "HR", 65000.00, date(2019, 3, 10)),
("Bob Johnson", "Finance", 80000.00, date(2018, 7, 22)),
("Alice Brown", "IT", 78000.00, date(2021, 1, 5))
]
cursor.executemany(insert_sql, employees)
# 提交事务
db.commit()
print(cursor.rowcount, "records inserted")
cursor.close()
db.close()
这段代码用cursor的execute函数,执行响应的insert sql语句。最关键的是db.commit函数,由于本例展示的并不是自动提交,所以一定要记得commit。不然数据不会真正保存到数据库中。
查询数据
# 查询所有数据
cursor.execute("SELECT * FROM employees")
result = cursor.fetchall()
print("All employees:")
for row in result:
print(row)
# 带条件查询
department = "IT"
cursor.execute("SELECT * FROM employees WHERE department = %s", (department,))
it_employees = cursor.fetchall()
print(f"\nEmployees in {department} department:")
for emp in it_employees:
print(emp)
cursor.close()
db.close()
查询数据时,执行完execute函数,调用cursor的fetchall函数,返回一个结果集,类型是列表。然后遍历这个列表,获得一条条类型为元组的记录。
更新和删除数据
更新和删除数据就不再这里展示,除sql语句不同,代码跟插入数据并没有太大的区别,网上也有其他相关例子
总结
这篇展示了python 连接mysql数据库,插入数据和查询数据的方式。
猜你喜欢
- 2025-07-10 MySQL高性能注意事项简述(高性能mysql重点章节)
- 2025-07-10 MySQL触发器介绍(mysql触发器使用)
- 2025-07-10 2021年超详细的java学习路线总结—纯干货分享
- 2025-07-10 MySQL常见错误及解决方法(mysql常见错误提示及解决方法)
- 2025-07-10 MySQL索引失效场景分析与优化(mysql索引何时失效)
- 2025-07-10 MySQL实战:聊聊子查询 vs 联表查询应该如何选择?
- 2025-07-10 SQL 神操作:用 LEFT JOIN 干掉 NOT IN,查询速度直接飙车!
- 2025-07-10 The entangled power of BRICS(the power of dreams)
- 2025-07-10 谁再在 SQL 中写 in 和 not in,直接走人!
- 2025-07-10 SQL面试题及答案( Top20)(mysql面试题及答案)
- 最近发表
-
- Vue3+Django4全新技术实战全栈项目|高清完结
- 工厂模式+策略模式消除 if else 实战
- 每天一个 Python 库:httpx异步请求,让接口测试飞起来
- 如何高效实现API接口的自动化测试?
- 前端工程化:从“手忙脚乱”到“从容协作”的进化记
- 使用C#创建服务端Web API(c#开发web服务器)
- SpringBoot之旅第四篇-web开发(springboot做web项目)
- 一文读懂SpringMVC(一文读懂新型政策性金融工具)
- Rust Web编程:第十二章 在 Rocket 中重新创建我们的应用程序
- Apache Druid 数据摄取——本地数据和kafka流式数据 一篇文章看懂
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)
- mysql数据库面试题 (57)