Python 獲取 Access 表字段名

時效說明:walker 的舊文遷移,某些地方可能過期,最後更新時間爲 2015-09-25

如下全部代碼 Python2.七、Python3.4 都可用。git

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,只須要填路徑。github

相關閱讀

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 ×
相關文章
相關標籤/搜索