以下所有代码Python2.7、Python3.4均可用。
一、win32.com
#author: walker #date: 2015-09-25 #function: 打印指定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(rs.Fields[i].Name + ' - ' + str(rs.Fields[i].Type) + ' - ' + str(rs.Fields[i].DefinedSize)) conn.Close()
关于字段类型(Type):3为数字,202为文本,203为备忘。
相关阅读:
0、win32com下载。
1、Python操作Access数据库基本操作步骤分析
2、ADO获取表的所有字段名
二、pyodbc
#encoding=utf-8 #author: walker #date: 2015-09-25 #function: 打印指定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()
相关链接:
1、pyodbc的pypi主页
2、pyodbc的文档
三、pypyodbc
#encoding=utf-8 #author: walker #date: 2015-09-25 #function: 打印指定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) row = cur.fetchone() for tup in row.cursor_description: print(tup[0]) cur.close() conn.close()
相关链接:
1、pypyodbc的pypi主页
2、pypyodbc的入门教程
3、未找到官方文档
四、pyodbc与pypyodbc取值的区别
(1)、在select指定字段时
row[idx] | row.field | row['field'] | row.get('field') | |
pyodbc | √ | √ | × | × |
pypyodbc | √ | × | √ | √ |
(2)、在select *时
row[idx] | row.field | row['field'] | row.get('field') | |
pyodbc | √ | × | × | × |
pypyodbc | √ | × | √ | √ |
*** walker * Updated 2015-09-25 ***