当我尝试使用cursor.primaryKeys("tablename")
时,发生了异常:
Error: ('IM001', '[IM001] [Microsoft][ODBC Driver Manager] Driver does not support this function (0) (SQLPrimaryKeys)')
list(cursor.columns(table='tablename'))
也不会显示主键。
对于访问 ODBC,我们通常可以通过 pyodbc cursor
对象的 .statistics() 方法获取主键列:
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'}
*编辑:此方法假定表的主键索引名为 PrimaryKey
。如果使用 MS Access 表生成器 (GUI) 创建表,则为真,但如果使用 DDL(即 CREATE TABLE …
)创建表,则不为真。在这些情况下,主键索引的名称类似于 Index_EA5344E1_0942_445C
因此上述方法不起作用,但我们可以使用 ACE DAO 代替:
import win32com.client # needs `pip install pywin32`
def get_access_primary_key_columns(db_path, table_name):
db_engine = win32com.client.Dispatch("DAO.DBEngine.120")
db = db_engine.OpenDatabase(db_path)
tbd = db.TableDefs(table_name)
for idx in tbd.Indexes:
if idx.Primary:
return [fld.Name for fld in idx.Fields]
if __name__ == "__main__":
print(
get_access_primary_key_columns(
r"C:UsersPublicDatabase1.accdb", "team"
)
)
# ['city', 'prov']
这是使用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)