mysql.connector操作mysql的blob值

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.

时间: 2024-08-10 00:05:49

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

mysql常用操作 mysql备份与恢复

先登录mysql  ==>mysql -uroot -p 查看数据库的版本 select version(); 查看有哪些库 show datases; 查看当前处于哪个库 select database(); 查看当前登录用户 select user(); 查看某个库下面的表: use db; show tables; 查看表的字段: desc dong; 创建库 create database db1; 创建表 create  table  tb1 (`id` int(4),`name`ch

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

From: http://www.cnblogs.com/magicsoar/p/3817518.html C++通过mysql的c api和通过mysql的Connector C++ 1.1.3操作mysql的两种方式 使用vs2013和64位的msql 5.6.16进行操作 项目中使用的数据库名为booktik 表为book ………. (共有30条记录,只列出了部分记录,14-30未列出) 一.通过mysql的C api进行操作 1.新建一个空项目 2.将D:\Program Files\M

[mysql] C++操作mysql方法

下载:http://mirrors.sohu.com/mysql/MySQL-5.5/ From: http://www.cnblogs.com/magicsoar/p/3817518.html C++通过mysql的c api和通过mysql的Connector C++ 1.1.3操作mysql的两种方式 使用vs2013和64位的msql 5.6.16进行操作 项目中使用的数据库名为booktik 表为book ---. (共有30条记录,只列出了部分记录,14-30未列出) 一.通过mys

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

Connector/Net 6.9.8 选择.net/mono即可,不需要安装. 将对应版本的MySql.Data.dll复制到bin目录下即可使用 http://dev.mysql.com/downloads/connector/net/ 但是在使用过程中,用mysql的like语句检索中文时,总是检索不到数据.原来是需要这是字符编码. using MySql.Data.MySqlClient; string query = @"(SELECT * from TB where title LI

VS2017 用MySQL Connector 链接 MySQL时 getString异常问题

原帖地址:http://www.sunnyu.com/?p=418 getString始终异常 异常代码类似: ResultSet res; ... res->getString(NAME); 经查询为basic_streambuf类中一个输出函数的指针错误. 更改为: ResultSet res; ... res->getString(NAME).c_str(); 运行即可. 原文地址:https://www.cnblogs.com/mintcoder/p/9147779.html

Developing DataBase Applications Using MySQL Connector/C++ 中文文本

Developing DataBase Applications Using MySQL Connector/C++ 中文文本 ? by grayondream 翻译自mysql Connector C++帮助文档[http://download.csdn.net/detail/midle110/4931166] ? 本教程将利用从MySQL数据库中链接,插入和检索数据的简单示例向您展示构建和安装MySQL Connector / C ++驱动程序的基本步骤.因为本文的重点是使用C++ Conn

python操作mysql数据库

连接数据库 输入值 存入数据库 关闭 import string import mysql.connector conn=mysql.connector.connect(user='root',password='test',database='dalian',use_unicode=True) cursor=conn.cursor() a=raw_input('enter an id: ') b=raw_input('enter a name: ') while(a!='quit' or b!

Visual Studio 2015编译64位MySQL Connector/C++

目前MySQL Connector/C++的binary版本最高只支持VS2008,VS2015需要下载源码自行编译. 尽管MySQL手册提供了信息,但在编译过程中还是有不少细节需要注意. CMAKE 到官网下载最新的稳定版本 把bin目录添加到环境变量PATH中 Boost 同样到官网下载最新的稳定版本 MySQL客户端库 MySQL客户端库头文件在MySQL目录下的include目录中 是的,编译connector还需要下载一个MySQL Server 添加环境变量MYSQL_DIR,值为M

python + docker, 实现天气数据 从FTP获取以及持久化(二)-- python操作MySQL数据库

前言 在这一节中,我们主要介绍如何使用python操作MySQL数据库. 准备 MySQL数据库使用的是上一节中的docker容器 “test-mysql”. Python 操作 MySQL 我们使用的IDE是 “神奇” 的 pycharm: 1. 首先新建一个python的项目,并且安装 “mysql-connector-python”. “mysql-connector-python” 是MySQL官方对于python的数据驱动,感兴趣的童鞋可以移步这里: https://dev.mysql