Python将一个文件夹的文件装载到MySQL数据库BLOB列,并将BLOB列下载到另一个文件夹

import os
import mysql.connector

# get all files inside a specific folder
dir_path = r'C:/Users/Administrator/PycharmProjects/pythonProject9/InputFiles/'
for path in os.scandir(dir_path):
    if path.is_file():
        print(path.name)
        with open(dir_path+path.name, 'rb') as file:
            binaryData = file.read()
            try:
                connection = mysql.connector.connect(host='localhost',
                                                     database='blob',
                                                     user='root',
                                                     password='root')

                cursor = connection.cursor()
                sql_insert_blob_query = """ INSERT INTO pybindata
                                  (name, data) VALUES (%s,%s)"""



                # Convert data into tuple format
                insert_blob_tuple = (path.name, binaryData)
                result = cursor.execute(sql_insert_blob_query, insert_blob_tuple)
                connection.commit()
                print("Image and file inserted successfully as a BLOB into python_employee table", result)

            except mysql.connector.Error as error:
                print("Failed inserting BLOB data into MySQL table {}".format(error))

            finally:
                if connection.is_connected():
                    cursor.close()
                    connection.close()
                    print("MySQL connection is closed")
import mysql.connector

dir_path = r'C:/Users/Administrator/PycharmProjects/pythonProject9/DownLoadFiles/'
print("Reading BLOB data from python_employee table")

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='blob',
                                         user='root',
                                         password='root')

    cursor = connection.cursor()
    sql_fetch_blob_query = """SELECT * from pybindata"""

    cursor.execute(sql_fetch_blob_query)
    record = cursor.fetchall()
    for row in record:
        print("Id = ", row[0], )
        print("Name = ", row[2])
        print("Storing employee image and bio-data on disk \n")
        with open(dir_path + row[2], 'wb') as file:
            file.write(row[1])

except mysql.connector.Error as error:
    print("Failed to read BLOB data from MySQL table {}".format(error))

finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值