如何将python类转换为表postgres

伊万

我一直在寻找关于如何从 Python 类中在数据库中制作表格的信息,但我没有找到很好的解释

我正在寻找示例,但描述有限,示例很难理解

我想在不使用sqlalchemy等框架的情况下实现

class User:
   tablename = "user"
   name = CharField(..)



def create_table(
    sql_query: str, 
    conn: psycopg2.extensions.connection, 
    cur: psycopg2.extensions.cursor
) -> None:
    try:
        # Execute the table creation query
        cur.execute(sql_query)
    except Exception as e:
        print(f"{type(e).__name__}: {e}")
        print(f"Query: {cur.query}")
        conn.rollback()
        cur.close()
    else:
        # To take effect, changes need be committed to the database
        conn.commit()

类 User -> postgres 表

阿德里安·克拉弗

如果您想沿着这条路线走下去,请查看attrs

@attr.s
class C(object):
    x = attr.ib(type=int)
    y = attr.ib(type=str)

flds = attr.fields(C)

flds
(Attribute(name='x', default=NOTHING, validator=None, repr=True, eq=True, order=True, hash=None, init=True, metadata=mappingproxy({}), type=<class 'int'>, converter=None, kw_only=False),
 Attribute(name='y', default=NOTHING, validator=None, repr=True, eq=True, order=True, hash=None, init=True, metadata=mappingproxy({}), type=<class 'str'>, converter=None, kw_only=False))

flds[0].name
'x'
flds[0].type 
int

要添加元数据,例如表名,请参阅元数据

您必须创建一个转换代码,该代码接受 Python 类型并映射到 SQL 类型字符串。

老实说,我的建议是不要用自己的自制解决方案走这条路。有很多 ORM 可以为您执行此操作,而无需让您的代码保持最新状态。如果你想要更小的东西,那么 SQLAlchemy 看看peewee

我自己的偏好是使用Sqitch将我的 DDL 保留为 SQL 脚本

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章