首页 技术 正文
技术 2022年11月7日
0 收藏 657 点赞 629 浏览 3936 个字

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:

 

1234 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 .

 

1234567891011121314151617181920212223242526 from mysql.connector import MySQLConnection, Errorfrom 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.

 

12345 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.

 

12 SELECT * FROM authorsWHERE 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:

 

123 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:

 

1234567891011121314151617181920212223 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.

 

12345 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.

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,999
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,511
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,357
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,140
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,770
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,848