def read_file(filename): with open(filename, 'rb') as f: photo = f.read() return photoCode language: Python (python)
其次,创建一个名为的新函数,该函数更新由 指定的作者的照片。update_blob()author_id
from mysql.connector import MySQLConnection, Errorfrom python_mysql_dbconfig import read_db_configdef 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()Code language: Python (python)
让我们详细检讨代码:
请把稳,我们从 MySQL 连接器/Python 包中导入了工具,并从我们在上一教程中开拓的模块中导入了函数。MySQLConnectionErrorread_db_config()python_mysql_dbconfig

让我们测试一下函数。update_blob()
def main(): update_blob(144, "pictures\garth_stein.jpg")if __name__ == '__main__': main()Code language: Python (python)
请把稳,您可以利用以下照片并将其放入图片文件夹中进行测试。
在 main 函数中,我们调用该函数来更新 id 为 144 的作者的照片列。为了验证结果,我们从表中选择数据。update_blob()authors
SELECT FROM authorsWHERE id = 144;Code language: Python (python)
它按预期事情。
在 Python 中读取 BLOB 数据在此示例中,我们从表中选择 BLOB 数据并将其写入文件。authors
首先,开拓一个将二进制数据写入文件的函数:write_file()
def write_file(data, filename): with open(filename, 'wb') as f: f.write(data)Code language: Python (python)
其次,创建一个名为 的新函数:read_blob()
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()Code language: Python (python)
该函数从表中读取数据,并将其写入参数指定的文件中。read_blob()BLOBauthorsfilename
代码很大略:
首先,编写一个检索特定作者照片的 SELECT 语句。其次,通过调用函数获取数据库配置。read_db_config()第三,连接到数据库,实例化游标,然后实行查询。收到数据后,我们利用函数将其写入由 .BLOBwrite_file()filename末了,关闭游标和数据库连接。以下代码测试该函数:read_blob()
def main(): read_blob(144,"output\garth_stein.jpg")if __name__ == '__main__': main()Code language: Python (python)
如果您打开项目中的输出文件夹并在那里看到图片,则表示您已成功从数据库中读取 。BLOB
在本教程中,我们向您展示了如何利用MySQL Connector / API从Python更新和读取MySQL中的BLOB数据。