从MS Access中提取外键

Extracting Foreign Keys from MS Access(从MS Access中提取外键)
本文介绍了从MS Access中提取外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从MS Access中的表中获取所有外键。当尝试使用cursor.ForeignKeys(&Q;表&Q;)时,我收到错误:

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

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

推荐答案

尽管Access ODBC驱动程序不支持SQLForeignKeys函数,但您仍然可以通过Jet/ACEDAO:

获取该信息
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:UsersPublicDatabase1.accdb", "child"))
    """
    [{'constrained_columns': ['parent_id'], 
      'referred_table': 'parent', 
      'referred_columns': ['id'], 
      'name': 'parentchild'}]
    """

这篇关于从MS Access中提取外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)