Python操作PostgreSQL

Python连接PostgreSQL简单操作

依赖:psycopg2

# !/usr/bin/env python3
# _*_ encoding: utf-8 _*_
# Time     :2021-02-25 10:12
# ++++++++++++++++++++++++++++++++++++++++++++++++++
# 调用.sql文件 执行
# 使用方法 python3 handleDB.py  
# param:文件名称
# ++++++++++++++++++++++++++++++++++++++++++++++++++
import configparser
import datetime
import os
import sys
import time
from functools import wraps

import psycopg2

workPath = "/data/etl/ETLAuto"


def decorator(function):
    @wraps(function)
    def inner(*args, **kwargs):
        try:
            print('当前运行:', function.__name__)
            return function(*args, **kwargs)
        except Exception as e:
            print(e.args[-1])
            sys.exit(-1)

    return inner


def echoRuntime(func):
    def wrapper(*args, **kwargs):
        startTime = time.time()
        func(*args, **kwargs)
        endTime = time.time()
        messcs = (endTime - startTime)
        print(func.__name__ + ' running time is : %.4f' % messcs)

    return wrapper


class HandleDB(object):
    """docstring for HandleDB"""

    def __init__(self, file_path=None):
        super(HandleDB, self).__init__()
        if file_path:
            configpath = file_path
        else:
            configpath = workPath + '/app/conf.ini'
            print(configpath)
        self.cf = configparser.ConfigParser()
        self.cf.read(configpath)

    def execute_sql(self, sqlCode):
        """:param 连接数据库"""
        host = self.cf.get('test', 'host')
        port = self.cf.get('test', 'port')
        user = self.cf.get('test', 'user')
        password = self.cf.get('test', 'password')
        database = self.cf.get('test', 'database')
        with psycopg2.connect(host=host, port=port, user=user, password=password, database=database) as conn:
            with conn.cursor() as cursor:
                cursor.execute(sqlCode)
                # print(cursor.fetchall())

    def get_tableName(self, tablename):
        tmp_ls = tablename.split('.')[0].split('_')
        return '_'.join(tmp_ls)

    def read_sqlfile(self):
        sqlpath = '%s/app/sql/' % workPath
        if (sys.argv[1].find('.dir') == -1):
            sqlfile = sys.argv[1]
        else:
            sqlfile = self.get_tableName(sys.argv[1])
        print(sqlpath)
        # sqlfile = sys.argv[1]
        if not os.path.exists(sqlpath):
            os.makedirs(sqlpath)
        else:
            pass
        with open(sqlpath + sqlfile + '.sql', 'r', encoding='utf-8', errors='ignore') as f:
            sqlCode = f.read()
            print('执行语句:', sqlCode)
            self.execute_sql(sqlCode)


@echoRuntime
@decorator
def main():
    print('开始执行::%s' % (datetime.datetime.now()))
    obj = HandleDB()
    obj.read_sqlfile()
    print('执行结束:%s' % (datetime.datetime.now()))


if __name__ == '__main__':
    main()

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值