python - 如何将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 表
解决方案
您必须连接到数据库并使用 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。
推荐阅读
- c# - 使用 dotnet test cli 的净核心覆盖率始终为 0%
- tfs - TFS 关注不发送电子邮件
- powershell - PowerBI New-PowerBIReport Powershell cmdlet 错误“任务已取消。”
- docker - 将单个 docker-compose.yml 文件与 Docker Compose 和 Stack 一起使用,利弊?
- azure - 表单识别器 Azure - 无法获取 TypeError
- android - 复制可打包数据对象
- javascript - 尝试通过对象数组中动态添加的属性/值进行过滤并保存到状态
- r - 在 R 中反转 persp3D 图中的颜色
- r - facet_wrap_paginate x 轴偏离最后一页的位置
- python - 使用双向 LSTM 的形状的 ValueError