時效說明: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() 關(guān)于字段類型(Type):3為數(shù)字,,202為文本,203為備忘,。Windows 下有更簡潔的函數(shù) pypyodbc.win_connect_mdb,,只需要填路徑。 相關(guān)閱讀 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() 相關(guān)鏈接 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 #是否將字段名轉(zhuǎn)為小寫 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() 相關(guān)鏈接 pyodbc 與 pypyodbc 取值的區(qū)別 在 select 指定字段時 row[idx] row.field row['field'] row.get('field') pyodbc √ √ × × pypyodbc √ × √ √ 在 select * 時 row[idx] row.field row['field'] row.get('field') pyodbc √ × × × pypyodbc √ × √ √ |
|