在SQLAlchemy中使用BLOB的示例

时间:2009-11-22 19:28:05

标签: sqlalchemy blob

有没有人举例说明如何在SQLAlchemy中使用BLOB?

此致 史蒂夫

4 个答案:

答案 0 :(得分:18)

from sqlalchemy import *
from sqlalchemy.orm import mapper, sessionmaker
import os

engine = create_engine('sqlite://', echo=True)
metadata = MetaData(engine)

sample = Table(
    'sample', metadata,
    Column('id', Integer, primary_key=True),
    Column('lob', Binary),
)

class Sample(object):

    def __init__(self, lob):
        self.lob = lob

mapper(Sample, sample)

metadata.create_all()

session = sessionmaker(engine)()

# Creating new object
blob = os.urandom(100000)
obj = Sample(lob=blob)
session.add(obj)
session.commit()
obj_id = obj.id
session.expunge_all()

# Retrieving existing object
obj = session.query(Sample).get(obj_id)
assert obj.lob==blob

答案 1 :(得分:7)

from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

from struct import *

_DeclarativeBase = declarative_base()

class MyTable(_DeclarativeBase):
    __tablename__ = 'mytable'
    id = Column(Integer, Sequence('my_table_id_seq'), primary_key=True)
    my_blob = Column(BLOB)

DB_NAME = 'sqlite:///C:/BlobbingTest.db'
db = create_engine(DB_NAME)
#self.__db.echo = True
_DeclarativeBase.metadata.create_all(db)
Session = sessionmaker(bind=db)
session = Session()

session.add(MyTable(my_blob=pack('H', 365)))
l = [n + 1 for n in xrange(10)]
session.add(MyTable(my_blob=pack('H'*len(l), *l)))
session.commit()

query = session.query(MyTable)
for mt in query.all():
    print unpack('H'*(len(mt.my_blob)/2), mt.my_blob)

答案 2 :(得分:0)

从文档中可以看出BINARY:http://docs.sqlalchemy.org/en/latest/dialects/mysql.html

  

class sqlalchemy.dialects.mysql.BLOB(length = None)基础:   sqlalchemy.types.LargeBinary

     

SQL BLOB类型。

     

init (length = None)构造一个LargeBinary类型。

     

参数:length - 可选,DDL中使用的列的长度   对于那些接受长度(即MySQL)的BLOB类型的语句。它   不生成一个加长的BINARY / VARBINARY类型 - 使用   BINARY / VARBINARY专门为那些类型。可以安全地省略   如果没有CREATE TABLE将被发出。某些数据库可能需要a   在DDL中使用的长度,并且在CREATE时会引发异常   表DDL已发布。

答案 3 :(得分:0)

您为什么不使用LargeBinary

摘自:https://docs.sqlalchemy.org/en/13/core/type_basics.html#sqlalchemy.types.LargeBinary

class sqlalchemy.types.LargeBinary(length=None)
A type for large binary byte data.

The LargeBinary type corresponds to a large and/or unlengthed binary type for the target platform, such as BLOB on MySQL and BYTEA for PostgreSQL. It also handles the necessary conversions for the DBAPI.

我相信这可以为您提供帮助。