Python如何把照片存入mysql数据库
时间: 2024-02-16 20:04:21 浏览: 127
将照片存入MySQL数据库需要进行以下步骤:
1. 安装MySQL数据库和Python的MySQL驱动
2. 建立数据库和表
3. 将照片转换为二进制格式
4. 使用Python代码将二进制数据存入MySQL数据库
下面是一个示例代码:
```python
import pymysql
from PIL import Image
# 建立数据库连接
db = pymysql.connect(host='localhost', user='root', password='password', db='test')
# 创建游标对象
cursor = db.cursor()
# 建立图片表
create_table_sql = """CREATE TABLE `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`data` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"""
cursor.execute(create_table_sql)
# 将图片转换为二进制
with open("example.jpg", "rb") as f:
img_data = f.read()
# 插入数据
insert_sql = "INSERT INTO `images`(`name`, `data`) VALUES (%s, %s)"
cursor.execute(insert_sql, ("example", img_data))
# 提交数据并关闭连接
db.commit()
cursor.close()
db.close()
```
在这个示例代码中,我们使用了Pillow库将图片转换为二进制格式,然后使用Python的MySQL驱动将二进制数据存入MySQL数据库中的`images`表中。
阅读全文
相关推荐


















