sqlalchemy python中的Blob文件

时间:2019-11-29 06:54:43

标签: python sqlalchemy

有人可以向我展示有关如何使用sqlalchemy保存和检索blob文件的清晰过程吗?我很难理解这个过程。

1 个答案:

答案 0 :(得分:1)

BLOB只是一个bytes对象,我们可以像存储其他列类型一样进行存储和检索。表格示例

create table employee (
    id int identity primary key, 
    lastname nvarchar(50), 
    firstname nvarchar(50), 
    photo varbinary(max));

将会

import sqlalchemy as sa

connection_url = "mssql+pyodbc://@localhost,49242/myDb?driver=ODBC+Driver+17+for+SQL+Server"
engine = sa.create_engine(connection_url)

new_hire = {'lastname': 'Thompson', 'firstname': 'Gord'}
with open('C:/Users/Gord/Pictures/HeadShot.jpg', 'rb') as f:
    new_hire['photo'] = f.read()

employee = sa.Table('employee', sa.MetaData(), autoload=True, autoload_with=engine)

# insert
ins = employee.insert().values(new_hire)
result = engine.execute(ins)
new_id = result.inserted_primary_key[0]
print(f"row saved with id = {new_id}")

# retrieve
sel = employee.select(employee.c.id == new_id)
result = engine.execute(sel)
row = result.fetchone()
retrieved_photo = row['photo']

# check
print('ok' if retrieved_photo == new_hire['photo'] else 'FAIL')