连接数据库

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值