Python使用pymysql存储和读取文件_第一版

#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'yangshijin'

# coding=utf-8
""" 测试代码(mysql存储文件) """
import pymysql
 
# TODO 需要z自行替换的字段
DBName = 'model_save' # 数据库
tabel_name = 'models'	# 数据库_表格
columnName = 'xxxx'	# 存储文件字段名称,类型:longblob
inDoc = './py4.jpg'	# 需要存入数据库的文件路径
#inDoc = './沧海一声笑.mp3'	# 需要存入数据库的文件路径
outDoc = './py4_dump.jpg'	# 从数据库读取后恢复的文件路径
#outDoc = './沧海一声笑_dump_1.mp3'	# 从数据库读取后恢复的文件路径
info = 'py_img4'
#info = '沧海一声笑'

def connect():
    """ 连接数据库 """
    conn = pymysql.connect('localhost',
                           'root',
                           'eve136712',
                           db=DBName,
                           charset='utf8',
                           use_unicode=True)
    return conn
 
def openFile(fileName):
    """ 打开文件,读取二进制格式,返回处理过的字符串 """
    with open(fileName, 'rb') as f:
        #print(f.read())
        content = 's'.join([str(ele) for ele in f.read()])
        f.close()
    return content or ''
 
def dealDBFileData(data):
    """ 对从数据库fetchall的二进制进行处理 """
    temp = data[0][1].decode('ascii').split('s')
    return bytes([int(ele) for ele in temp])
 
if __name__ == '__main__':
    conn = connect()
    cursor = conn.cursor()
    # 打开文件,读取二进制
    text = openFile(inDoc)
 
    #===========将数据存储到数据库===========
    insert_sql="INSERT INTO models (model, info) VALUES  (%s, %s)"
    if cursor.execute(insert_sql , (text, info)):
        conn.commit()
        print('=====写入成功=====')
    else:
        print('=====写入失败=====\n', cursor.error)
 
    #===========从数据库获取数据===========
    select_sql = 'select * from models where id=1'
    if cursor.execute(select_sql):
        res = cursor.fetchall()
        # 对读取的二进制进行处理
        text = dealDBFileData(res)
 
        # 将二进制写入新文件
        with open(outDoc, 'wb') as f2:
            f2.write(text)
            f2.close()
            print('=====读取成功=====')
            cursor.close()
            conn.close()

 

你可能感兴趣的:(Python,mysql,python,pymysql)