目录
环境
读取图片
创建存放图片的表
存入MySQL
保存MySQL查询得到的图片数据为图片
实现代码
测试结果
首页 后端开发 Python教程 怎么用Python程序实现向MySQL存放图片

怎么用Python程序实现向MySQL存放图片

Apr 19, 2023 pm 03:16 PM
mysql python

环境

Python 3.7.4
pymysql
8.0.11 MySQL Community Server
登录后复制

读取图片

以二进制格式读取图片

with open("./test.jpg", "rb") as file:
	image = file.read()
登录后复制

创建存放图片的表

存放图片字段的属性为longblog,即long binary large object

def create_image_table(self):
	sql = 'create table if not exists picture ( \
        image longblob);'

    try:
        self.cursor.execute(sql)

        self.connection.commit()

    except pymysql.Error:
        print(pymysql.Error)
登录后复制

存入MySQL

将二进制格式的图片数据存入MySQL

def insert_image(self, image):
    sql = "insert into picture(image) values(%s)"
    self.cursor.execute(sql, image)
    self.connection.commit()
登录后复制

保存MySQL查询得到的图片数据为图片

以二进制的格式写出图片

def get_image(self, path):
    sql = 'select * from picture'
    try:
        self.cursor.execute(sql)
        image = self.cursor.fetchone()[0]
        with open(path, "wb") as file:
            file.write(image)
    except pymysql.Error:
        print(pymysql.Error)
    except IOError:
        print(IOError)
登录后复制

实现代码

import pymysql


class Database():
	
	'''
		Description:
			database demo to store image in MySQL RDBMS
		Attributes:
			None
	'''
    
    def __init__(self):
        self.connection = pymysql.connect(host=&#39;<host name>&#39;,user=&#39;<user name>&#39;,passwd=&#39;<password>&#39;,db=&#39;<database name>&#39;,charset=&#39;utf8&#39;)
        self.cursor = self.connection.cursor()

	&#39;&#39;&#39;
		Description:
			create table to store images
		Args:
			None
		Return:
			None
	&#39;&#39;&#39;
    
    def create_image_table(self):
        sql = &#39;create table if not exists picture ( \
            image longblob);&#39;

        try:
            self.cursor.execute(sql)

            self.connection.commit()

        except pymysql.Error:
            print(pymysql.Error)
	
	&#39;&#39;&#39;
		Description:
			insert image into table
		Args:
			image:
				image to store
		Returns:
			None
	&#39;&#39;&#39;

    def insert_image(self, image):
        sql = "insert into picture(image) values(%s)"
        self.cursor.execute(sql, image)
        self.connection.commit()
	
	&#39;&#39;&#39;
		Description:
			get image from database
		Args:
			path:
				path to save image
		Returns:
			None
	&#39;&#39;&#39;	

    def get_image(self, path):
        sql = &#39;select * from picture&#39;
        try:
            self.cursor.execute(sql)
            image = self.cursor.fetchone()[0]
            with open(path, "wb") as file:
                file.write(image)
        except pymysql.Error:
            print(pymysql.Error)
        except IOError:
            print(IOError)
            
	&#39;&#39;&#39;
		Description:
			destruction method
		Args:
			None
		Returns:
			None
	&#39;&#39;&#39;
	
    def __del__(self):
        self.connection.close()
        self.cursor.close()

if __name__ == "__main__":
    database = Database()
    # read image from current directory
    with open("./test.jpg", "rb") as file:
        image = file.read()

    database.create_image_table()
    database.insert_image(image)

    database.get_image(&#39;./result.jpg&#39;)
登录后复制

测试结果

怎么用Python程序实现向MySQL存放图片

以上是怎么用Python程序实现向MySQL存放图片的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

phpmyadmin怎么打开 phpmyadmin怎么打开 Apr 10, 2025 pm 10:51 PM

可以通过以下步骤打开 phpMyAdmin:1. 登录网站控制面板;2. 找到并点击 phpMyAdmin 图标;3. 输入 MySQL 凭据;4. 点击 "登录"。

2小时的Python计划:一种现实的方法 2小时的Python计划:一种现实的方法 Apr 11, 2025 am 12:04 AM

2小时内可以学会Python的基本编程概念和技能。1.学习变量和数据类型,2.掌握控制流(条件语句和循环),3.理解函数的定义和使用,4.通过简单示例和代码片段快速上手Python编程。

phpmyadmin连接mysql phpmyadmin连接mysql Apr 10, 2025 pm 10:57 PM

如何使用 phpMyAdmin 连接到 MySQL?访问 phpMyAdmin 的 URL,通常为 http://localhost/phpmyadmin 或 http://[您的服务器 IP 地址]/phpmyadmin。输入您的 MySQL 用户名和密码。选择您要连接的数据库。点击 "连接" 按钮以建立连接。

Redis如何查看服务器版本 Redis如何查看服务器版本 Apr 10, 2025 pm 01:27 PM

问题:如何查看 Redis 服务器版本?使用命令行工具 redis-cli --version 查看已连接服务器的版本。使用 INFO server 命令查看服务器内部版本,需解析返回信息。在集群环境下,检查每个节点的版本一致性,可使用脚本自动化检查。使用脚本自动化查看版本,例如用 Python 脚本连接并打印版本信息。

redis怎么启动服务器 redis怎么启动服务器 Apr 10, 2025 pm 08:12 PM

启动 Redis 服务器的步骤包括:根据操作系统安装 Redis。通过 redis-server(Linux/macOS)或 redis-server.exe(Windows)启动 Redis 服务。使用 redis-cli ping(Linux/macOS)或 redis-cli.exe ping(Windows)命令检查服务状态。使用 Redis 客户端,如 redis-cli、Python 或 Node.js,访问服务器。

redis怎么读取队列 redis怎么读取队列 Apr 10, 2025 pm 10:12 PM

要从 Redis 读取队列,需要获取队列名称、使用 LPOP 命令读取元素,并处理空队列。具体步骤如下:获取队列名称:以 "queue:" 前缀命名,如 "queue:my-queue"。使用 LPOP 命令:从队列头部弹出元素并返回其值,如 LPOP queue:my-queue。处理空队列:如果队列为空,LPOP 返回 nil,可先检查队列是否存在再读取元素。

为什么要使用mysql?利益和优势 为什么要使用mysql?利益和优势 Apr 12, 2025 am 12:17 AM

选择MySQL的原因是其性能、可靠性、易用性和社区支持。1.MySQL提供高效的数据存储和检索功能,支持多种数据类型和高级查询操作。2.采用客户端-服务器架构和多种存储引擎,支持事务和查询优化。3.易于使用,支持多种操作系统和编程语言。4.拥有强大的社区支持,提供丰富的资源和解决方案。

phpMyAdmin全面使用指南 phpMyAdmin全面使用指南 Apr 10, 2025 pm 10:42 PM

phpMyAdmin不仅仅是数据库管理工具,它能让你深入理解MySQL,提升编程技巧。核心功能包括CRUD和SQL查询执行,理解SQL语句的原理至关重要。高级技巧包括导出/导入数据和权限管理,需要深入的安全理解。潜在问题包括SQL注入,解决方案是参数化查询和备份。性能优化涉及SQL语句优化和索引使用。最佳实践强调代码规范、安全实践和定期备份。

See all articles