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()

已标记关键词 清除标记
相关推荐
<p> <strong><span style="font-size:20px;color:#FF0000;">本课程主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的Java学习者</span></strong> </p> <p> <span style="color:#FF0000;"><strong><span style="font-size:18px;">1. 包含:<span style="color:#FFFF00;background-color:#FF0000;">项目源码、</span><span style="color:#FFFF00;background-color:#FF0000;">项目文档、数据库脚本、软件工具</span>等所有资料</span></strong></span> </p> <p> <span style="color:#FF0000;"><strong><span style="font-size:18px;">2. 手把手的带你从零开始部署运行本套系统</span></strong></span> </p> <p> <span style="color:#FF0000;"><strong><span style="font-size:18px;">3. 该项目附带的源码资料可作为毕设使用</span></strong></span> </p> <p> <span style="color:#FF0000;"><strong><span style="font-size:18px;">4. 提供技术答疑和远程协助指导</span></strong></span><strong><span style="font-size:18px;"></span></strong> </p> <p> <br /> </p> <p> <span style="font-size:18px;"><strong>项目运行截图:</strong></span> </p> <p> <strong><span style="font-size:18px;">1)系统登陆界面</span></strong> </p> <p> <strong><span style="font-size:18px;"><img src="https://img-bss.csdn.net/202002241015433522.png" alt="" /><br /> </span></strong> </p> <p> <strong><span style="font-size:18px;"><strong><span style="font-size:18px;">2)学生模块</span></strong></span></strong> </p> <p> <strong><span style="font-size:18px;"><img src="https://img-bss.csdn.net/202002241015575966.png" alt="" /></span></strong> </p> <p> <strong><span style="font-size:18px;"><strong><span style="font-size:18px;">3)教师模块</span></strong></span></strong> </p> <p> <strong><span style="font-size:18px;"><img src="https://img-bss.csdn.net/202002241016127898.png" alt="" /></span></strong> </p> <p> <strong><span style="font-size:18px;"><strong><span style="font-size:18px;">4)系统管理员</span></strong></span></strong> </p> <p> <strong><span style="font-size:18px;"><img src="https://img-bss.csdn.net/202002241016281177.png" alt="" /></span></strong> </p> <p> <strong><span style="font-size:18px;"><img src="https://img-bss.csdn.net/202002241016369884.png" alt="" /></span></strong> </p> <p> <strong><span style="font-size:18px;"><br /> </span></strong> </p> <p> <strong><span style="font-size:18px;"><strong><span style="font-size:18px;">更多Java毕设项目请关注我的毕设系列课程 <a href="https://edu.csdn.net/lecturer/2104">https://edu.csdn.net/lecturer/2104</a></span></strong></span></strong> </p> <p> <strong><span style="font-size:18px;"><br /> </span></strong> </p>
©️2020 CSDN 皮肤主题: 黑客帝国 设计师:白松林 返回首页