python操作postgresql数据库

  之前在公司学习用python操作mysql数据库,但是实际上我们公司一直用的是postgresql数据库,所以我寻思着照葫芦画瓢也写一个python操作postgresql的工具类吧!这里用到了psycopg2模块

直接上代码:

import psycopg2
class PostGreSQL:
    # 初始化
    def __init__(self, dataBaseName, userName, password, host, port):
        self.dataBaseName = dataBaseName
        self.userName = userName
        self.password = password
        self.host = host
        self.port = port

        self._conn = self.GetConnect()
        if self._conn:
            self._cur = self._conn.cursor()

    # 获取数据库连接对象
    def GetConnect(self):
        conn = False
        try:
            conn = psycopg2.connect(
                database=self.dataBaseName,
                user=self.userName,
                password=self.password,
                host=self.host,
                port=self.port
            )
        except Exception as err:
            print("连接数据库失败,%s" % err)
        return conn
    # 执行查询sql
    def ExecQuery(self, sql):
        res = ""
        try:
            self._cur.execute(sql)
            res = self._cur.fetchall()
        except Exception as err:
            print("查询失败, %s" % err)
        else:
            return res

    # 执行增删改sql
    def ExceNonQuery(self, sql):
        flag = False
        try:
            self._cur.execute(sql)
            self._conn.commit()
            flag = True
        except Exception as err:
            flag = False
            self._conn.rollback()
            print("执行失败, %s" % err)
        else:
            return flag

    def GetConnectInfo(self):
        print("连接信息:")
        print("服务器:%s , 用户名:%s , 数据库:%s " % (self.host, self.userName, self.dataBaseName))

 

posted @ 2019-11-11 00:15  风车车与车车风  阅读(2266)  评论(0编辑  收藏  举报