从Python连接到Access

时间:2012-10-06 15:46:14

标签: python database ms-access ms-access-2007

  

可能重复:
  How to connect pyodbc to an Access (.mdb) Database file

我希望从Python连接到数据库Boreas(Access)。如何从Python连接到Access数据库Northwind?

1 个答案:

答案 0 :(得分:3)

以下是两种方式,使用COM发送和odbc。您将需要pywin32扩展和/或pyodbc来使用这些方法。

import win32com.client
import pyodbc

def ado():
    '''
    connect with com dispatch objs
    '''
    conn = win32com.client.Dispatch(r'ADODB.Connection')
    DSN = ('PROVIDER = Microsoft.Jet.OLEDB.4.0;DATA SOURCE = ' + db +  ';')
    conn.Open(DSN)

    rs = win32com.client.Dispatch(r'ADODB.Recordset')
    strsql = "select * from deer"
    rs.Open(strsql, conn, 1, 3)
    t = rs.GetRows()
    conn.Close()
    return t

def odbc():
    '''
    connects with odbc
    '''        
    constr = 'Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=' + db
    conn = pyodbc.connect(constr, autocommit=True)
    cur = conn.cursor()
    strsql = "select * from deer"
    cur.execute(strsql)
    t = list(cur)
    conn.close()
    return t

if __name__ == '__main__':

    db = 'c:/work/deer/deer.mdb'
    data1 = ado()
    data2 = odbc()
祝你好运,

麦克