Select column names in a table using PyODBC

喜你入骨 提交于 2020-01-01 14:25:18

问题


I'm writing a Python program that selects some data from a Microsoft Access mdb file using PyODBC.

I need to discover the column names of several different tables. In SQL Server, this can be accomplished by using a query like

SELECT c.name FROM sys.columns c, sys.tables t
WHERE c.object_id = t.object_id
AND t.name = tableName

But that query doesn't work in Access. With

SELECT MSysObjects.Name FROM MSysObjects
WHERE (((MSysObjects.Flags)=0) AND ((MSysObjects.Type)=1))
ORDER BY MSysObjects.Name

I can get a list of non-linked table names, but MSysObject doesn't seem to contain a list of column names.

Is there a way to use SQL to grab the column names of a table in an Access database?


回答1:


I was unable to find an SQL query to accomplish this. However, I did discover that PyODB has a cursor method that can return a list of columns

# columns in table x
for row in cursor.columns(table='x'):
    print row.column_name



回答2:


I'm not sure about the limitations in querying that version of MS-Access, but a solution I've seen used in other similar situations is to SELECT * FROM table LIMIT = 0 (or 1 depending). You are then able to gather the returned column names from the result.




回答3:


Python 3

To access by conlumn name

table_row = conn.execute(query)
for row in table_rows:
     print (row.nameColumn)

To access by conlumn index

table_row = conn.execute(query)
for row in table_rows:
     print (row[0])


来源:https://stackoverflow.com/questions/4227836/select-column-names-in-a-table-using-pyodbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!