consolidator
/
MdbHelper.py
86 строк · 3.1 Кб
1import os2import sys3from typing import Any4import pyodbc5import pandas as pd6import subprocess7
8class MdbHelper(object):9"""Класс для работы с БД MS Access (.mdb)10
11Args:
12object (_type_): _description_
13"""
14version = "2.1.0"15
16def __init__(self,mdb_path:str,autoconnect:bool=False) -> None:17try:18self.cur_path = sys._MEIPASS19except:20self.cur_path = os.path.dirname(os.path.realpath(__file__))21self.mdb_sql = f"{self.cur_path}\\mdbt\\mdb-sql.exe"22self.mdm_query = f"{self.cur_path}\\mdbt\\mdm.sql"23self.dump_path = f"{self.cur_path}\\mdbt\\dump.csv"24self.csv_delim = ";"25self.mdb_path = mdb_path26self.connection = None27drivers = [i for i in pyodbc.drivers() if i.startswith('Microsoft Access Driver')]28# self.connection_str=f"Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};Dbq={mdb_path};Uid=;Pwd=;"29try:30self.connection_str=f"Driver={{{drivers[0]}}};Dbq={mdb_path};Uid=;Pwd=;"31except: pass32if autoconnect:33self.connection = pyodbc.connect(self.connection_str)34print("conncected")35
36def connect(self):37try:38self.connection = pyodbc.connect(self.connection_str)39print("conncected")40except: raise41
42def db_info(self)-> Any:43try:44return self.connection.getinfo(pyodbc.SQL_DRIVER_NAME)45except Exception as exp:46raise exp47
48# def table_list(self)->list[str]:49# try:50# sql = "SELECT Name FROM MSysObjects WHERE Type=1 AND Flags=0"51# tables = self.connection.execute(sql).fetchall()52# table_names = [str(table.Name) for table in tables]53# return table_names54# except: raise55
56def get_table_df(self,table:str) ->pd.DataFrame:57""" Получение датафрейма из MSAccess (mdb) посредством odbc """58try:59sql = f"select * from [{table}]"60return self.get_sql_df(sql)61except: raise62
63def get_mdbt_table_df(self) ->pd.DataFrame:64""" Получение датафрейма из MSAccess (mdb) посредством mdbtools65issue http://vsys01775:8282/flea/pyexcelcons3/-/issues/1
66iisue http://vsys01775:8282/flea/pyexcelcons3/-/issues/9
67"""
68try:69dt = subprocess.check_output([self.mdb_sql, "-i", self.mdm_query, "-o", self.dump_path, f"--delim={self.csv_delim}", "-P", self.mdb_path], shell=True,encoding="cp1251")70df = pd.read_csv(self.dump_path,delimiter=self.csv_delim,header=0,encoding="cp1251",skipfooter=1)71return df72except: raise73
74
75def get_sql_df(self,sql)->pd.DataFrame:76try:77df = pd.read_sql(sql,con=self.connection)78return df79except: raise80
81def close_connection(self,autocommit:bool=True):82try:83if autocommit: self.connection.commit()84self.connection.close()85print("disconnected")86except: raise87