使用python对图片进行写入数据库并从数据库中读取的操作

前言

有时我们往往得把图片写入数据库。然后我发现网上写成的比较系统的比较难找。然后就自己摸索了一下,写下这篇博客。由于接触不多,所以若有不对的地方请各位海涵。


版本说明

python 3.7.6
mysql Ver 14.14 Distrib 5.7.30, for Win64 (x86_64)
pymysql 0.10.0


建个数据库

打开命令行,登录后一下语句建立个名为images的数据库。

create database images;

cmd

然后新建一个表格名为images(也可以起个其他的名字)

create table images
(
	id int auto_increment,
	data mediumblob null,
	name varchar(50) null,
	constraint images_pk
		primary key (id)
);

建好后的数据库结构如下:
在这里插入图片描述这里要注意字段名字最好不要命名为MySQL的关键字,比如describe,如果硬要这样,那么久得再下面的代码

sql = "INSERT INTO images (data, name) VALUES (%s, '{0}')".format(filename)

改为

sql = "INSERT INTO images (data, `describe`) VALUES (%s, '{0}')".format(filename)

这里的 ` 是ESC键下面的那个键。

操作的函数如下:

import pymysql
import os
import traceback


def write_pic2mysql(path, config):
    """
    读取图片写入数据库
    :param path: 读取的图片的路径
    :param config: 数据库连接配置信息
    :return: None
    """
    filename = path.split('/')[-1]
    try:
        with open(path, 'rb') as f:
            img = f.read()
    except:
        print('读取失败')
        # sys.exit(1)
        return
    try:
        conn = pymysql.connect(host=config['host'],
                               port=config['port'],
                               user=config['user'],
                               passwd=config['password'],
                               db=config['db'],
                               charset='utf8',
                               use_unicode=True)
        cursor = conn.cursor()

		# 注意一下这里的 {0} 的引号,可以试一下去掉引号会提醒没有者找到该字段
        sql = "INSERT INTO images (data, name) VALUES (%s, '{0}')".format(filename)
        cursor.execute(sql, img)
        conn.commit()
        cursor.close()
        conn.close()
        print('写入 {} 成功'.format(filename))

    except Exception as e:
        print(e)
        print('写入失败')


def read_mysql2pic(path, filename, config):
    """
    从数据库中读取图片
    :param path: 你要保存的图片的路径
    :param filename:你要从数据库读取的名字,在本例子相当于数据库中的name字段
    :param config: 数据库连接配置信息
    :return: None
    """
    try:
        conn = pymysql.connect(host=config['host'],
                               port=config['port'],
                               user=config['user'],
                               passwd=config['password'],
                               db=config['db'],
                               charset='utf8',
                               use_unicode=True)
        cursor = conn.cursor()
        cursor.execute("select data from images where name = '{}'".format(filename))
        res = cursor.fetchone()[0]
        with open(path, 'wb') as f:
            f.write(res)
        print('从数据库中读取 {} 成功'.format(filename))
    except Exception as e:
        print(e)
        print('读取数据库中的图片失败')


if __name__ == '__main__':
    my_config = {
    
    'host': 'localhost', 'port': 3306, 'user': 'root',
                 'password': 'root', 'db': 'images'}
  	write_pic2mysql('files/pic.jpg', my_config)
  	print(' 写入后再读取 '.center(50, '*'))
    read_mysql2pic('files/read_pic.jpg', 'pic.jpg', my_config)

可以看到这里将files文件夹下的图片pic.jpg先写入数据库再读取并保存图片到本地的files文件夹下并命名为read_pic.jpg。

运行前:
文件夹下:
文件夹下

扫描二维码关注公众号,回复: 11874844 查看本文章

运行后:
终端输出:
控制台

文件夹下:
文件夹下

数据库:
数据库中


结语

好了介绍就到这里。感谢您的观看。有问题请留言哦。

猜你喜欢

转载自blog.csdn.net/weixin_43850253/article/details/108104815