python3图片转换二进制存入mysql
时间:2023-05-18 07:06:50
首先,在数据库中创建一个表,用于存放图片:
CREATE TABLE Images(Id INT PRIMARY KEY AUTO_INCREMENT, Data MEDIUMBLOB);
然后运行如下PYTHON代码进行:
# -*- coding: UTF-8 -*-
import MySQLdb as mdb
import sys
try:
#用读文件模式打开图片
fin = open("../web.jpg")
#将文本读入img对象中
img = fin.read()
#关闭文件
fin.close()
except IOError, e:
#如果出错,打印错误信息
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
try:
#链接mysql,获取对象
conn = mdb.connect(host='localhost',user='root',passwd='root', db='test')
#获取执行cursor
cursor = conn.cursor()
#直接将数据作为字符串,插入数据库
cursor.execute("INSERT INTO Images SET Data='%s'" % mdb.escape_string(img))
#提交数据
conn.commit()
#提交之后,再关闭cursor和链接
cursor.close()
conn.close()
except mdb.Error, e:
#若出现异常,打印信息
print "Error %d: %s" % (e.args[0],e.args[1])
标签:python3,图片转换二进制存,mysql
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python详细对比讲解break和continue区别
2022-08-09 08:45:05
11个Python3字典内置方法大全与示例汇总
2021-11-26 22:33:51
![](https://img.aspxhome.com/file/2023/2/99472_0s.jpg)
总结几个非常实用的Python库
2023-02-28 11:39:54
JavaScript解决Joseph问题
2008-06-21 17:11:00
python查看列的唯一值方法
2021-09-20 07:25:46
基于mysql多实例安装的深入解析
2024-01-21 01:59:27
asp Access数据备份,还原,压缩类代码
2011-03-07 11:16:00
还不知道Anaconda是什么?读这一篇文章就够了
2022-02-19 01:36:50
![](https://img.aspxhome.com/file/2023/9/114639_0s.png)
python广度优先搜索得到两点间最短路径
2023-09-05 02:06:24
![](https://img.aspxhome.com/file/2023/1/88981_0s.jpg)
解决Python 进程池Pool中一些坑
2023-12-21 00:24:31
关于MySQL 优化的100个的建议
2024-01-19 12:31:39
![](https://img.aspxhome.com/file/2023/7/129887_0s.png)
node.js中的fs.realpathSync方法使用说明
2024-05-13 09:59:04
Python如何使用ConfigParser读取配置文件
2023-11-03 03:05:30
浅谈python迭代器
2023-07-21 21:56:47
Mysql查询时间区间日期列表实例代码
2024-01-17 16:17:32
![](https://img.aspxhome.com/file/2023/1/65301_0s.png)
Flask交互基础(GET、 POST 、PUT、 DELETE)的使用
2022-01-17 11:00:04
![](https://img.aspxhome.com/file/2023/8/79808_0s.png)
最简便的备份MySQL数据库的方法
2008-12-25 13:16:00
关于vue中hash和history的区别与使用图文详解
2024-05-13 09:14:31
![](https://img.aspxhome.com/file/2023/1/126421_0s.png)
后台程序开发常用jQuery插件
2010-04-06 12:11:00
Python进阶学习修改闭包内使用的外部变量
2023-04-09 01:23:04
![](https://img.aspxhome.com/file/2023/1/112931_0s.png)