mysql Compress()与sqlalchemy [英] mysql Compress() with sqlalchemy
本文介绍了mysql Compress()与sqlalchemy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
表:
id (整数主键)
数据(blob)
table:
id(integer primary key)
data(blob)
我使用mysql和sqlalchemy. 要插入数据,我使用:
I use mysql and sqlalchemy. To insert data I use:
o = Demo()
o.data = mydata
session.add(o)
session.commit()
我想这样插入到表中:
INSERT INTO table(data) VALUES(COMPRESS(mydata))
如何使用sqlalchemy做到这一点?
How can I do this using sqlalchemy?
推荐答案
您可以将SQL函数分配给属性:
you can assign a SQL function to the attribute:
from sqlalchemy import func
object.data = func.compress(mydata)
session.add(object)
session.commit()
下面是使用与数据库无关的lower()函数的示例:
Here's an example using a more DB-agnostic lower() function:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
Base= declarative_base()
class A(Base):
__tablename__ = "a"
id = Column(Integer, primary_key=True)
data = Column(String)
e = create_engine('sqlite://', echo=True)
Base.metadata.create_all(e)
s = Session(e)
a1 = A()
a1.data = func.lower("SomeData")
s.add(a1)
s.commit()
assert a1.data == "somedata"
您可以使用@validates将其自动设置:
you can make it automatic with @validates:
from sqlalchemy.orm import validates
class MyClass(Base):
# ...
data = Column(BLOB)
@validates("data")
def _set_data(self, key, value):
return func.compress(value)
如果希望在刷新之前可以在python中读取它,则需要在本地进行记忆并使用描述符进行访问.
if you want it readable in python before the flush, you'd need to memoize it locally and use a descriptor to access it.
这篇关于mysql Compress()与sqlalchemy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文