首页 > 解决方案 > 如何将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()

类用户-> postgres 表

标签: pythonsqlpostgresqlormpsycopg2

解决方案


您必须连接到数据库并使用 postgresSQL 告诉数据库如何构造表。只需使表属性与您的类属性相同。

您的表 SQL 将类似于:

 CREATE TABLE [IF NOT EXISTS] table_name (
       class_attribute datatype(length) column_constraint,
       class_attribute datatype(length) column_constraint,
       class_attribute datatype(length) column_constraint,
       table_constraints
    );

如果您想编写自己的 postgresSQL DBMS 接口,您将需要非常了解关系数据库。如果您决定想要一个现成的解决方案,请尝试psycopg


推荐阅读