简体   繁体   English

有没有办法使用 python 字典在数据库中创建表?

[英]Is there a way to create tables in a DB using python Dictionary?

I have a large dictionary of items - ~400 columns.我有一个很大的项目字典 - 约 400 列。 I have a script to detect and create the type of each item so I have {'age' = INT, "Name" = String,etc..) but I'm not sure how to use that to create a table in SQLAlchemy or directly creating the query?我有一个脚本来检测和创建每个项目的类型,所以我有 {'age' = INT, "Name" = String,etc ..) 但我不确定如何使用它在 SQLAlchemy 或直接创建查询?

I am using postgres but I am familiar with mysql & sqlite so anything that works for those I would be able to apply to my usecase.我正在使用 postgres,但我熟悉 mysql 和 sqlite,所以任何对我有用的东西都可以应用于我的用例。

What about this:那这个呢:

from sqlalchemy import create_engine, Table, Column, MetaData
metadata = MetaData()
fields = (Column(colname, coltype) for colname, coltype in your_dict.items())
t = Table(name, metadata, *fields)
engine = create_engine(database)
metadata.create_all(engine)

You need to have objects from sqlalchemy.sql.sqltypes rather than strings as values in your_dict :你需要有从对象sqlalchemy.sql.sqltypes而不是字符串作为值your_dict

from sqlalchemy.sql.sqltypes import String, Integer

See https://docs.sqlalchemy.org/en/13/core/type_basics.html for the whole list.有关整个列表,请参阅https://docs.sqlalchemy.org/en/13/core/type_basics.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM