pyodbc - 从MS Access(MDB)数据库中读取主键

时间:2016-06-08 20:28:56

标签: python sql database ms-access pyodbc

当我尝试使用cursor.primaryKeys("tablename")时,会发生异常:

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

list(cursor.columns(table='tablename'))也不会显示主键。

2 个答案:

答案 0 :(得分:3)

对于Access ODBC,我们可以通过pyodbc .statistics对象的cursor方法获取主键列:

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'}

答案 1 :(得分:1)

这是使用pythonnet和Oledb Jet驱动程序的解决方案。请注意,这不会将主键的顺序保留为列:

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)