You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取PostgreSQL列类型常量?MySQL可通过Python库获取但Postgres的找不到

嘿,这个问题我刚好踩过坑!在PostgreSQL的Python生态里,确实不像MySQL的库(比如mysql-connector)那样直接给你打包好现成的列类型常量,但咱们有几种靠谱的方式来获取或者定义这些类型,下面给你拆解清楚:

方法一:用psycopg2获取原生类型信息

psycopg2是PostgreSQL最常用的Python驱动,它自带了不少和类型相关的工具,也能直接查询系统表拿到最权威的类型数据:

  • 查看内置类型映射
    psycopg2的psycopg2.extensions模块里有string_types和types两个字典,分别存储了OID到类型名称、类型对象的映射。你可以直接打印出来查看:

    import psycopg2
    from psycopg2.extensions import string_types
    
    # 遍历打印所有类型名称与对应的OID
    for oid, type_name in string_types.items():
        print(f"OID: {oid}, 类型名称: {type_name}")
    
  • 查询系统表pg_type
    PostgreSQL所有的类型元数据都存在系统表pg_type里,这是最直接获取完整类型列表的方式。你可以用psycopg2连接数据库后执行查询:

    import psycopg2
    
    # 替换成你的数据库连接信息
    conn = psycopg2.connect("dbname=your_db user=your_user password=your_pass host=your_host")
    cur = conn.cursor()
    
    # 过滤掉系统内部类型,只显示常用类型
    cur.execute("""
        SELECT typname, oid, typlen 
        FROM pg_type 
        WHERE typname NOT LIKE 'pg_%' AND typname NOT LIKE '_%'
        ORDER BY typname;
    """)
    types = cur.fetchall()
    
    for typname, oid, typlen in types:
        print(f"类型名称: {typname}, OID: {oid}, 长度: {typlen}")
    
    cur.close()
    conn.close()
    
方法二:用SQLAlchemy封装好的类型常量

如果你用ORM框架SQLAlchemy,它已经帮你封装好了PostgreSQL的几乎所有常用类型,直接导入就能用:

from sqlalchemy import Column, Integer
from sqlalchemy.dialects.postgresql import VARCHAR, BOOLEAN, JSONB, TIMESTAMP, UUID
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    username = Column(VARCHAR(50), unique=True)
    is_active = Column(BOOLEAN, default=True)
    preferences = Column(JSONB)
    created_at = Column(TIMESTAMP)
    uuid = Column(UUID)

要是想查看SQLAlchemy支持的所有PostgreSQL类型映射,还可以这样:

from sqlalchemy.dialects.postgresql import PGDialect

dialect = PGDialect()
type_map = dialect.type_map

for oid, type_cls in type_map.items():
    print(f"OID: {oid}, 类型类: {type_cls.__name__}")
额外小技巧:自定义类型常量字典

如果只是想在写原生SQL的时候避免硬编码类型名称,完全可以自己定义一个常量字典,用起来更顺手:

POSTGRESQL_TYPES = {
    'INTEGER': 'integer',
    'VARCHAR': 'varchar',
    'BOOLEAN': 'boolean',
    'JSONB': 'jsonb',
    'TIMESTAMP': 'timestamp',
    'UUID': 'uuid'
}

# 示例:用常量拼接SQL
sql = f"CREATE TABLE test (id {POSTGRESQL_TYPES['INTEGER']} PRIMARY KEY, name {POSTGRESQL_TYPES['VARCHAR']}(50));"

内容的提问来源于stack exchange,提问作者prideloki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:54:30