pyodbc - read primary keys from MS Access (MDB) database

不羁的心 提交于 2019-12-24 02:04:12

问题


When I try to use cursor.primaryKeys("tablename") then exception occurs:

Error: ('IM001', '[IM001] [Microsoft][ODBC Driver Manager] Driver does not support this function (0) (SQLPrimaryKeys)')

list(cursor.columns(table='tablename')) does not reveal primary keys either.


回答1:


For Access ODBC we can get the Primary Key columns via the .statistics method of the pyodbc cursor object:

crsr = conn.cursor()
table_name = 'MyTable'
# dict comprehension: {ordinal_position: col_name}
pk_cols = {row[7]: row[8] for row in crsr.statistics(table_name) if row[5]=='PrimaryKey'}
print(pk_cols)  # e.g., {1: 'InvID', 2: 'LineItem'}



回答2:


Here is solution using pythonnet and Oledb Jet driver. Note that this does not preserve the order of primary keys as columns:

import clr
import System
import System.Data.OleDb
from System.Data.OleDb import OleDbSchemaGuid

def getKeyNames(tableName, mdbname):
    conn = System.Data.OleDb.OleDbConnection()
    conn.ConnectionString = ("Provider=Microsoft.Jet.OLEDB.4.0;"
                         "Data source={}".format(mdbname))
    conn.Open()
    returnList=[]
    mySchema = (conn).GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys,
        [None, None, tableName])
    columnOrdinalForName = mySchema.Columns["COLUMN_NAME"].Ordinal
    for r in mySchema.Rows:
        returnList.append(r.ItemArray[columnOrdinalForName])
        conn.Close()
    return returnList

getKeyNames(table_name,mdbname)


来源:https://stackoverflow.com/questions/37712307/pyodbc-read-primary-keys-from-ms-access-mdb-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!