from sqlalchemy import create_engine
import pandas as pd
from typing import Dict
import sys,os
class communicate_with_MSSQL_DB(object):
def __init__(self,db_account_file): # input: database account info
self.account: Dict[str,str] = eval(open(os.path.join(sys.path[0],db_account_file)).read())
self.user = self.account['user']
self.passwd = self.account['passwd']
self.host= self.account['host']
# self.db = self.account['db']
# self.port = self.account['port']
def __enter__(self):
# include port
# self.engine = create_engine(r'mssql+pymssql://{}:{}@{}:{}'.format(self.user,self.passwd,self.host,self.port),connect_args={'autocommit': True})
# not include port
self.engine = create_engine(r'mssql+pymssql://{}:{}@{}'.format(self.user,self.passwd,self.host),connect_args={'autocommit': True})
#include db
# self.engine = create_engine(r'mssql+pymssql://{}:{}@{}/{}'.format(self.user,self.passwd,self.host,self.db),connect_args={'autocommit': True})
# print(r'mssql+pymssql://{}:{}@{}/{}'.format(self.user,self.passwd,self.host,self.db))
return self.engine
def __exit__(self,exc_class,exc,tracback):
self.engine.dispose()
class Query_MSSQL_DB():
def __init__(self,db_account_file): # input: database account info
self.db_account_file = db_account_file
def Loading_SQL(self,sql_file_name): # input: sql
work_dir = os.path.dirname(os.path.abspath(__file__))
path =os.path.join(work_dir,sql_file_name)
query_sql = open(path).read()
return query_sql
def pd_data_query(self,sql):
with communicate_with_MSSQL_DB(self.db_account_file) as engine:
query_result = pd.read_sql(sql,engine)
return query_result
def excute_sql(self,sql):
with communicate_with_MSSQL_DB(self.db_account_file) as engine:
engine.execute(sql)
if __name__ == '__main__':
q = Query_MSSQL_DB('数据库账号dict.txt')
sql = (q.Loading_SQL('query_dispatched_lot.sql')).format(start_time = '2022-05-31 10:00:00', end_time = '2022-05-31 10:10:00')
result = q.pd_data_query(sql)
print(result)
python连接数据库package