【问题标题】:Extracting Foreign Keys from MS Access从 MS Access 中提取外键
【发布时间】:2021-07-29 11:42:46
【问题描述】:

我正在尝试从 MS Access 中的表中获取所有外键。尝试使用 cursor.foreignKeys("Table") 时,出现错误:

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

这是一个类似的问题,但主键:pyodbc - read primary keys from MS Access (MDB) database

【问题讨论】:

    标签: python ms-access pyodbc


    【解决方案1】:

    尽管 Access ODBC 驱动程序不支持SQLForeignKeys 函数,您仍然可以通过 Jet/ACE DAO 获取该信息:

    import win32com.client  # needs `pip install pywin32`
    
    
    def get_access_foreign_keys(db_path, table_name):
        db_engine = win32com.client.Dispatch("DAO.DBEngine.120")
        db = db_engine.OpenDatabase(db_path)
        fk_list = []
        for rel in db.Relations:
            if rel.ForeignTable == table_name:
                fk_dict = {
                    "constrained_columns": [],
                    "referred_table": rel.Table,
                    "referred_columns": [],
                    "name": rel.Name,
                }
                for fld in rel.Fields:
                    fk_dict["constrained_columns"].append(fld.ForeignName)
                    fk_dict["referred_columns"].append(fld.Name)
                fk_list.append(fk_dict)
        return fk_list
    
    
    if __name__ == "__main__":
        print(get_access_foreign_keys(r"C:\Users\Public\Database1.accdb", "child"))
        """
        [{'constrained_columns': ['parent_id'], 
          'referred_table': 'parent', 
          'referred_columns': ['id'], 
          'name': 'parentchild'}]
        """
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多