Python 获取 Access 表字段名

更新于 2019-08-21  约 7 分钟
时效说明:walker 的旧文迁移,某些地方可能过时,最后更新时间为 2015-09-25

以下所有代码 Python2.7、Python3.4 均可用。

win32.com

# encoding: utf-8
# author: walker
# date: 2015-09-25
# summary: 打印指定access文件、指定表的所有字段

import win32com.client

def PrintColumns_win32com(pathfile, tablename):
    conn = win32com.client.Dispatch(r'ADODB.Connection')
    DSN = 'PROVIDER=Microsoft.ACE.OLEDB.12.0;DATA SOURCE=' + pathfile + ';'
    #DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=' + pathfile + ';'
    conn.Open(DSN)
      
    rs = win32com.client.Dispatch(r'ADODB.Recordset')
    rs.Cursorlocation = 3
    sql = 'SELECT TOP 1 * FROM ' + tablename
    print(sql)
    rs.Open(sql, conn)
    for i in range(0, rs.Fields.Count):
        print('%s - %d - %d' % (rs.Fields[i].Name, rs.Fields[i].Type, rs.Fields[i].DefinedSize))
      
    conn.Close()

关于字段类型(Type):3为数字,202为文本,203为备忘。Windows 下有更简洁的函数 pypyodbc.win_connect_mdb,只需要填路径。

相关阅读

pyodbc

# encoding: utf-8
# author: walker
# date: 2015-09-25
# summary: 打印指定access文件、指定表的所有字段

import pyodbc

def PrintColumns_pyodbc(pathfile, tablename):
    connStr = r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=%s;' % pathfile
    print('connStr:' + connStr)
    conn = pyodbc.connect(connStr)
    
    cur = conn.cursor()
    
    for row in cur.columns(table=tablename):
        print(row.column_name)
    
    cur.close()
    conn.close()

相关链接

pypyodbc

# encoding: utf-8
# author: walker
# date: 2015-09-25
# summary: 打印指定access文件、指定表的所有字段

import pypyodbc

def PrintColumns_pypyodbc(pathfile, tablename):
    connStr = r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=%s;' % pathfile
    print('connStr:' + connStr)
    pypyodbc.lowercase = False  #是否将字段名转为小写
    conn = pypyodbc.connect(connStr)
     
    cur = conn.cursor()
    cur.execute('SELECT TOP 1 * FROM ' + tablename)
    
    cnt = 0
    for tup in cur.description:
        print(tup[0])
        cnt += 1
    print('cnt:' + str(cnt))
     
    cur.close()
    conn.close()

相关链接

pyodbc 与 pypyodbc 取值的区别

  • 在 select 指定字段时
row[idx] row.field row['field'] row.get('field')
pyodbc × ×
pypyodbc ×
  • 在 select * 时
row[idx] row.field row['field'] row.get('field')
pyodbc × × ×
pypyodbc ×
阅读 477更新于 2019-08-21

推荐阅读
qbit snap
用户专栏

开箱即用,拿走不谢。

7 人关注
75 篇文章
专栏主页
目录