1 #!/usr/bin/env python 2 # -*- conding: utf-8 -*- 3 4 import pypyodbc 5 if __name__=="__main__": 6 7 str = 'Driver={Microsoft Access Driver (*.mdb)};DBQ=E:\123.mdb' 8 conn = pypyodbc.win_connect_mdb(str) 9 #conn = pypyodbc.connect(str) 10 cur = conn.cursor() 11 cur.execute("SELECT * FROM catalog") 12 for row in cur.fetchall(): 13 for field in row: 14 print field, 15 print '' 19 conn.commit() 20 cur.close() 21 conn.close()
注意这里使用的是pypyodbc.win_connect_mdb,如果使用pypyodbc.connect则会出现:
Traceback (most recent call last): File "E:odbc.py", line 6, in <module> conn = pypyodbc.connect(str) File "E:pypyodbc.py", line 2434, in __init__ self.connect(connectString, autocommit, ansi, timeout, unicode_results, read only) File "E:pypyodbc.py", line 2483, in connect check_success(self, ret) File "E:pypyodbc.py", line 988, in check_success ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi) File "E:pypyodbc.py", line 964, in ctrl_err raise Error(state,err_text) pypyodbc.Error: (u'IM002', u'[IM002] [Microsoft][ODBC u9a71u52a8u7a0bu5e8fu 7ba1u7406u5668] u672au53d1u73b0u6570u636eu6e90u540du79f0u5e76u4e14u 672au6307u5b9au9ed8u8ba4u9a71u52a8u7a0bu5e8f')
如果出现:
C:Python27python.exe E:/odbc.py Traceback (most recent call last): File "E:/odbc.py", line 5, in <module> conn = pypyodbc.win_connect_mdb(str) File "E:pypyodbc.py", line 2744, in win_connect_mdb return connect('Driver={'+driver_name+"};DBQ="+mdb_path, unicode_results = use_unicode, readonly = False) File "E:pypyodbc.py", line 2434, in __init__ self.connect(connectString, autocommit, ansi, timeout, unicode_results, readonly) File "E:pypyodbc.py", line 2483, in connect check_success(self, ret) File "E:pypyodbc.py", line 988, in check_success ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi) File "E:pypyodbc.py", line 964, in ctrl_err raise Error(state,err_text) pypyodbc.Error: (u'HY000', u'[HY000] [Microsoft][ODBC Microsoft Access Driver]u5e38u89c1u9519u8bef u65e0u6cd5u6253u5f00u6ce8u518cu8868u9879u201cTemporary (volatile) Ace DSN for process 0x19d8 Thread 0x17f0 DBC 0x36d00b8 Jetu201du3002')
则可能是此文件已加密
import pypyodbc,socket if __name__=="__main__": s = socket.socket() str = 'Driver={Microsoft Access Driver (*.mdb)};PWD=123;DBQ=E:\123.mdb' conn = pypyodbc.win_connect_mdb(str) #print conn.dbc_h #rec = conn.ConnectByDSN('E:\123.mdb',"yinsua",'123') #conn.ConnectByDSN("ORACLE-PYTHON","yinsua",123) cur = conn.cursor() cur.execute("SELECT * FROM catalog") for row in cur.fetchall(): for field in row: print field, print '' conn.commit() cur.close() conn.close()
只需在DBQ前面加上这么一段即可:PWD=YourPWD