使用 PyODBC 选择表中的列名

发布于 2024-10-03 05:51:19 字数 517 浏览 3 评论 0原文

我正在编写一个 Python 程序,该程序使用 PyODBC 从 Microsoft Access mdb 文件中选择一些数据。

我需要发现几个不同表的列名。在 SQL Server 中,这可以通过使用类似

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

但该查询在 Access 中不起作用的查询来完成。我

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

可以获得非链接表名称的列表,但 MSysObject 似乎不包含列名称列表。

有没有办法使用SQL来获取Access数据库中表的列名?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

枕花眠 2024-10-10 05:51:19

我无法找到 SQL 查询来完成此操作。但是,我确实发现 PyODB 有一个游标方法,可以返回列列表

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

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
痴骨ら 2024-10-10 05:51:19

Python 3

按列名称访问

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

按列索引访问

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

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])
甜柠檬 2024-10-10 05:51:19

我不确定查询该版本的 MS-Access 的限制,但我见过在其他类似情况下使用的解决方案是 SELECT * FROM table LIMIT = 0 (或 1,具体取决于)。然后,您可以从结果中收集返回的列名称。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文