SQLAlchemy 列类型

在创建表时,SQLAlchemy 支持使用以下四类列类型:

  • 通用类型
  • SQL 标准类型
  • 特定数据库专用类型
  • 自定义类型

通用类型

  • String(length=None, convert_unicode=False, assert_unicode=None) Python 字符串,数据库 varchar。
  • Unicode(length=None, **kwargs) Python unicode 对象,数据库 varchar。等同于 String(length, convert_unicode=True, assert_unicode=’warn’),在存储和读取时,会根据指定字符集编码和解码,默认使用 utf-8。
  • Text(length=None, convert_unicode=False, assert_unicode=None) Python 字符串,数据库 clob 或 text。
  • UnicodeText(length=None, **kwargs) Python unicode 对象。与 Text 的关系等同于 Unicode 与 String 的关系。
  • Integer(*args, **kwargs) Python 整型,数据库 int。
  • SmallInteger(*args, **kwargs) Python 整型,数据库 smallint。
  • Numeric(precision=10, scale=2, asdecimal=True, length=None) Python decimal.Decimal 对象,数据库 decimal 或 numeric。
  • Float(precision=10, asdecimal=False, **kwargs) Python float,数据库 float。
  • DateTime(timezone=False) Python datetime.datetime() 对象,数据库 datetime(sqlite 没有 datetime 型,所以存储为字符串,读取时重新被转换为 datetime.datetime())。
  • Date(*args, **kwargs) 不用说了。
  • Time(timezone=False) 不用说了。
  • Interval Python datetime.timedelta() 对象,PostgreSQL 有该类型,其它数据库则存储为相对于“纪元”(1970年1月1日)的一个日期。
  • Boolean(*args, **kwargs) Python 布尔,数据库 boolean 或 smallint。
  • Binary(length=None)
  • PickleType(protocol=2, pickler=None, mutable=True, comparator=None) 参考 http://linhs.blog.51cto.com/370259/126686http://peadrop.com/blog/2007/06/18/pickle-an-interesting-stack-language/

SQL 标准类型

某些类型不一定所有数据库都支持。

  • INT
  • INTEGER
  • CHAR
  • VARCHAR
  • NCHAR
  • TEXT
  • FLOAT
  • DECIMAL
  • TIMESTAMP
  • DATETIME
  • CLOB
  • BOOLEAN
  • SMALLINT
  • DATE
  • TIME

特定数据库专用类型

参考 sqlalchemy.databases。例如

1
2
3
4
5
6
7
8
9
10
11
from sqlalchemy.databases.mysql import MSBigInteger, MSEnum
table = Table('foo', meta,
    Column('id', MSBigInteger),
    Column('enumerates', MSEnum('a', 'b', 'c'))
)
 
from sqlalchemy.databases.postgres import PGInet, PGArray
table = Table('foo', meta,
    Column('ipaddress', PGInet),
    Column('elements', PGArray(str))
    )
  1. charms 说:

    有点高深啊,受用

  2. charms 说:

    这些代码可以用嘛?

  1. There are no trackbacks for this post yet.

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word