简体   繁体   English

如何在python中获取sqlsoup中的模式的列名?

[英]How to get column names of a schema in sqlsoup in python?

How do you get column names and types in a dictionary from a schema/table using SQLSOUP in python? 如何在python中使用SQLSOUP从模式/表中获取字典中的列名和类型? With MySQLDB I can create a cursor and use cursor.description. 使用MySQLDB,我可以创建一个游标并使用cursor.description。 is there some equivalent for sqlsoup? sqlsoup有一些等价物吗?

According to the documentation : 根据文件

A Table object can be instructed to load information about itself from the corresponding database schema object already existing within the database. 可以指示Table对象从数据库中已存在的相应数据库模式对象加载有关其自身的信息。 This process is called reflection. 这个过程叫做反射。 In the most simple case you need only specify the table name, a MetaData object, and the autoload=True flag. 在最简单的情况下,您只需指定表名,MetaData对象和autoload = True标志。 If the MetaData is not persistently bound, also add the autoload_with argument: 如果MetaData不是持久绑定的,还要添加autoload_with参数:

>>> messages = Table('messages', meta, autoload=True, autoload_with=engine)
>>> [c.name for c in messages.columns]
['message_id', 'message_name', 'date']

It appears that sqlsoup does have the ability to tell you the column names and types directly without going "underneath" to sqlalchemy. 似乎sqlsoup确实能够直接告诉你列名和类型而不用“下面”到sqlalchemy。 Table objects in sqlsoup have a member collection called 'c' that contains all the columns of the table, like so: sqlsoup中的表对象有一个名为“c”的成员集合,其中包含表的所有列,如下所示:

>>> import sqlsoup
>>> db =sqlsoup.SQLSoup('sqlite:///test.sqlite')
>>> db.example_table.c
<sqlalchemy.sql.expression.ColumnCollection object at 0x1059819d0>
>>> db.example_table.c.keys()
[u'column_1', u'column_2', u'column_3']
>>> db.example_table.c['column_1']
Column(u'column_1', VARCHAR(), table=<example_table>, primary_key=True, nullable=False)
>>> db.example_table.c['column_1'].type
VARCHAR()

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

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