在SQLAlchemy
的python类中,您必须为字符串变量指定最大字符长度。例如,url = Column(String(200))
我对存储大字符串感兴趣,但是当我尝试设置mytextfield = Column(String(2**30))
时,我收到以下错误:
OperationalError: (OperationalError) (1074, "Column length too big for column 'textfield' (max = 21845); use BLOB or TEXT instead") '\nCREATE TABLE users (\n\tid INTEGER NOT NULL AUTO_INCREMENT, \n\tname VARCHAR(50), \n\tfullname VARCHAR(50), \n\tpassword VARCHAR(12), \n\ttextfield VARCHAR(2147483648), \n\tPRIMARY KEY (id)\n)\n\n' ()
如何保留ascii编码但增加SQLAlchemy对象Base类中字符串的最大长度?如果我要切换到使用mytextfield = Column(UnicodeText(2**30))
的unicode,我认为这将默认为utf-8而不会增加标准英文字符的存储大小?如果它是在utf-8中并且我从SQL数据库中检索了一个条目,那么该文本是否等同于text = u'my text here'
,即使它最初是作为text = 'my text here'
输入的?
这是我目前的代码:
from sqlalchemy import create_engine
engine = create_engine("mysql://user:password@host/database")
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import Column, Integer, String, Sequence, UnicodeText
class User(Base):
__tablename__ = 'users'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
name = Column(String(50))
fullname = Column(String(50))
password = Column(String(12))
textfield = Column(String(length=2**31))
def __init__(self, name, fullname, password, textfield):
self.name = name
self.fullname = fullname
self.password = password
self.textfield = textfield
def __repr__(self):
return "<User('%s','%s', '%s', '%s')>" % (self.name, self.fullname, self.password, self.textfield)
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship, backref
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
email_address = Column(String(100), nullable=False)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship("User", backref=backref('addresses', order_by=id))
def __init__(self, email_address):
self.email_address = email_address
def __repr__(self):
return "<Address('%s')>" % self.email_address
Base.metadata.create_all(engine)
mytext = "Peter Piper picked a peck of pickled peppers. A peck of pickled peppers Peter Piper picked. If Peter Piper picked a peck of pickled peppers, Where's the peck of pickled peppers that Peter Piper picked?"
new_user = User('Pete', 'Peter Piper', 'peppy', mytext)
from sqlalchemy.orm import sessionmaker
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
session.add(new_user)
session.commit()
答案 0 :(得分:4)
使用Text或UnicodeText代替字符串或Unicode。
文本映射到CLOB(TEXT)字段,可以存储大量数据 字符串映射到VARCHAR字段,通常限制为2 ^ 31-1