This tutorial shows you how to work with MySQL BLOB data in Python, with examples of updating and reading BLOB data.

The  authors table has a column named  photo whose data type is BLOB. We will read data from a picture file and update to the photo column.

Updating BLOB data in Python

First, we develop a function named  read_file() that reads a file and returns the file’s content:

 
1
2
3
4
def read_file(filename):
    with open(filename, 'rb') as f:
        photo = f.read()
    return photo

Second, we create a new function named  update_blob() that updates photo for an author specified by author_id .

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
 
def update_blob(author_id, filename):
    # read file
    data = read_file(filename)
 
    # prepare update query and data
    query = "UPDATE authors " \
            "SET photo = %s " \
            "WHERE id  = %s"
 
    args = (data, author_id)
 
    db_config = read_db_config()
 
    try:
        conn = MySQLConnection(**db_config)
        cursor = conn.cursor()
        cursor.execute(query, args)
        conn.commit()
    except Error as e:
        print(e)
    finally:
        cursor.close()
        conn.close()

Let’s examine the code in detail:

  1. First, we call the  read_file() function to read data from a file and return it.
  2. Second, we compose an UPDATE statement that updates photo column for an author specified by author_id . The  args variable is a tuple that contains file data andauthor_id . We will pass this variable to the  execute() method together with the query .
  3. Third, inside the  try except block, we connect to the database, instantiate a cursor, and execute the query with args . To make the change effective, we call commit() method of the MySQLConnection object.
  4. Fourth, we close the cursor and database connection in the  finally block.

Notice that we imported MySQLConnection and Error objects from the MySQL Connector/Python package and  read_db_config() function from the  python_mysql_dbconfig module that we developed in the previous tutorial.

Let’s test the  update_blob() function.

 
1
2
3
4
5
def main():
    update_blob(144, "pictures\garth_stein.jpg")
 
if __name__ == '__main__':
    main()

Notice that you can use the following photo and put it into the pictures folder for testing.

Inside the main function, we call the  update_blob() function to update the photo column for the author with id 144. To verify the result, we select data from the  authors table.

 
1
2
SELECT * FROM authors
WHERE id = 144;

It works as expected.

Reading BLOB data in Python

In this example, we select BLOB data from the  authors table and write it into a file.

First, we develop a  write_file() function that write a binary data into a file as follows:

 
1
2
3
def write_file(data, filename):
    with open(filename, 'wb') as f:
        f.write(data)

Second, we create a new function named  read_blob() as below:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def read_blob(author_id, filename):
    # select photo column of a specific author
    query = "SELECT photo FROM authors WHERE id = %s"
 
    # read database configuration
    db_config = read_db_config()
 
    try:
        # query blob data form the authors table
        conn = MySQLConnection(**db_config)
        cursor = conn.cursor()
        cursor.execute(query, (author_id,))
        photo = cursor.fetchone()[0]
 
        # write blob data into a file
        write_file(photo, filename)
 
    except Error as e:
        print(e)
 
    finally:
        cursor.close()
        conn.close()

The  read_blob() function reads BLOB data from the  authors table and write it into a file specified by the  filename parameter.

The code is straightforward:

  1. First, we compose a SELECT statement that retrieves photo of a specific author.
  2. Second, we get the database configuration by calling the  read_db_config() function.
  3. Third, inside the  try except block, we connect to the database, instantiate cursor, and execute the query. Once we got the BLOB data, we use the  write_file() function to write it into a file specified by the filename .
  4. Fourth, in the finally block, we close the cursor and database connection.

Now, let’s test the  read_blob() function.

 
1
2
3
4
5
def main():
    read_blob(144,"output\garth_stein.jpg")
 
if __name__ == '__main__':
    main()

If you open the output folder in the project and see a picture there, it means that you have successfully read the blob from the database.

mysql.connector操作mysql的blob值的更多相关文章

  1. mysql常用操作 mysql备份与恢复

    先登录mysql  ==>mysql -uroot -p  查看数据库的版本 select version(); 查看有哪些库 show datases; 查看当前处于哪个库 select da ...

  2. python操作三大主流数据库(3)python操作mysql③python操作mysql的orm工具sqlaichemy安装配置和使用

    python操作mysql③python操作mysql的orm工具sqlaichemy安装配置和使用 手册地址: http://docs.sqlalchemy.org/en/rel_1_1/orm/i ...

  3. centos LAMP第四部分mysql操作 忘记root密码 skip-innodb 配置慢查询日志 mysql常用操作 mysql常用操作 mysql备份与恢复 第二十二节课

    centos  LAMP第四部分mysql操作  忘记root密码  skip-innodb 配置慢查询日志 mysql常用操作  mysql常用操作 mysql备份与恢复   第二十二节课 mysq ...

  4. [mysql] C++操作mysql方法总结(1)

    From: http://www.cnblogs.com/magicsoar/p/3817518.html C++通过mysql的c api和通过mysql的Connector C++ 1.1.3操作 ...

  5. [mysql] C++操作mysql方法

    下载:http://mirrors.sohu.com/mysql/MySQL-5.5/ From: http://www.cnblogs.com/magicsoar/p/3817518.html C+ ...

  6. python导入模块报错:ImportError: No module named mysql.connector(安装 mysql)

    python的版本是 $ python --version Python 2.7.12 报错代码如下 import mysql.connector 报错信息是 ImportError: No modu ...

  7. MySql Connector/Net Mysql like 搜索中文的问题(c#和asp.net连接mysql)

    Connector/Net 6.9.8 选择.net/mono即可,不需要安装. 将对应版本的MySql.Data.dll复制到bin目录下即可使用 http://dev.mysql.com/down ...

  8. python操作mysql数据库的常用方法使用详解

    python操作mysql数据库 1.环境准备: Linux 安装mysql: apt-get install mysql-server 安装python-mysql模块:apt-get instal ...

  9. Python使用MySQLConnector/Python操作MySQL、MariaDB数据库

    使用MySQL Connector/Python操作MySQL.MariaDB数据库   by:授客 QQ:1033553122 因目前MySQLdb并不支持python3.x,而MySQL官方已经提 ...

随机推荐

  1. Tesla P4 在深度学习上的性价比辗压目前所有量产的FPGA

    7000的价格, 5.5T FP, 75W不到的功耗,性能接近M40,敢问目前有哪个量产的FPGA能做到?还不算开发和维护的难度...KU115光PCIE+DMA+DDR4 controller+AX ...

  2. ubuntu下 too many file open 异常

    后台高并发或者多线程的情况下,无论是操作数据库还是操作文件,应用报出 too many file open 异常,其原因是受宿主系统文件数的限制.问题解决方式如下: 第一步:检查所在系统的文件数限制 ...

  3. WeedFS0.6.8-引用库列表

    WeedFS 0.68新增了对cassandra数据库存储的支持及JSON Web Token(JWTs)安全的支持. github.com/gocql/gocql //filer/cassandra ...

  4. noSuchMethodException问题

    上午遇到一个nosuchMethodException 折腾了一上午发现是jar包冲突引起的.首先发现单独运行没问题,和其他项目整合后就有问题,当时以为代码问题,其实早该想到是jar包冲突造成的... ...

  5. nginx的优化

    Nginx 优化 Nginx是俄罗斯人编写的十分轻量级的HTTP服务器,Nginx,它的发音为"engine X",是一个高性能的HTTP和反向代理服务器,同时也是一个IMAP/P ...

  6. php实现只保留mysql中最新1000条记录

    这篇文章主要介绍了php实现只保留mysql中最新1000条记录的方法和相关示例及数据库结构,十分的全面,有需要的小伙伴可以参考下. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 1 ...

  7. linux命令行下载jdk

      官网JDK7下载地址 http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html 在里面 ...

  8. Flex 对象克隆

    package widget.EnvPlot{ public class copyObject extends Object    {        public function copyObjec ...

  9. oracle、mysql新增字段,字段存在则不处理

    oracle: 表名:CHANNEL_TRADE_DETAIL列名:exchange_code declare v_rowcount integer; begin select count(*) in ...

  10. 循序渐进Python3(十二) --1--  web框架之django

    Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为: 大而全,框架本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能 ...