前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >python3连接postgresql工具类

python3连接postgresql工具类

作者头像
静谧星空TEL
发布于 2022-01-05 13:51:25
发布于 2022-01-05 13:51:25
1.8K00
代码可运行
举报
运行总次数:0
代码可运行

目录

一、环境准备

1、python3安装

2、MongoDB4安装

二、安装驱动

1、psycopg2驱动安装

2、pymogo驱动测试

三、py工具类

1、工具脚本

一、环境准备

postgresql官网:https://www.postgresql.org

postgresql中文社区:http://www.postgres.cn/index.php/v2/home

postgresql12中文手册:http://www.postgres.cn/docs/12/index.html

菜鸟教学:https://www.runoob.com/postgresql/postgresql-syntax.html

1、python3安装

windows离线安装python3.6.8环境:https://cloud.tencent.com/developer/article/1929280

Linux 离线安装 python 3.6.10:https://cloud.tencent.com/developer/article/1818613

2、MongoDB4安装

win10安装postgresql:https://cloud.tencent.com/developer/article/1929286

linux安装postgresql:https://cloud.tencent.com/developer/article/1818708

二、安装驱动

1、psycopg2驱动安装

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
pip install psycopg2

2、pymogo驱动测试

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
python
import psycopg2

三、py工具类

1、工具脚本

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#-*- encoding: utf-8 -*-

import psycopg2

class PGSQLUtil:
    """
    PostgreSQL工具类
    """
    def __init__(self, host="127.0.0.1", user=None, password=None, database=None, port=5432, dsn=None, connection_factory=None, cursor_factory=None, **kwargs):
        """构造函数"""
        self.__database = database
        self.__conn = psycopg2.connect(host=host, user=user, password=password, database=database, port=str(port),
                                       dsn=dsn, connection_factory=connection_factory, cursor_factory=cursor_factory, **kwargs)
        self.__cursor = self.__conn.cursor()

    def __del__(self):
        """析构函数"""
        self.__cursor.close()
        self.__conn.close()

    def get_conn(self):
        """获取连接"""
        return self.__conn

    def get_cursor(self):
        """获取游标"""
        return self.__cursor

    def list_databases(self, vars=None):
        """查询所有数据库"""
        self.__cursor.execute("SELECT pg_database.datname FROM pg_database", vars)
        dbs = []
        for db in self.__cursor.fetchall():
            dbs.append(db[0])
        return dbs

    def list_user_tables(self, vars=None):
        """查询当前用户所有表"""
        self.__cursor.execute("SELECT tablename FROM pg_tables WHERE schemaname='public'", vars)
        # self.__cursor.execute("SELECT * FROM  information_schema.tables WHERE table_schema='public'", vars)
        tables = []
        for table in self.__cursor.fetchall():
            tables.append(table[0])
        return tables

    def list_tables_privileges(self, vars=None):
        """查询所有表的权限"""
        self.__cursor.execute("SELECT * FROM  information_schema.table_privileges", vars)
        return self.__cursor.fetchall()

    def execute(self, sql, vars=None):
        """获取SQL执行结果"""
        self.__cursor.execute(sql, vars)
        return self.__cursor.fetchall()

    def get_version(self, vars=None):
        """获取MySQL版本"""
        self.__cursor.execute("SELECT VERSION()", vars)
        version = self.__cursor.fetchone()
        print("Postgresql Version : %s" % version)
        return version[0]

    def list_table_metadata(self, vars=None):
        """查询所有表的元数据信息"""
        sql = "SELECT * FROM information_schema.TABLES WHERE TABLE_TYPE !='SYSTEM VIEW' AND TABLE_SCHEMA NOT IN ('sys','mysql','information_schema','performance_schema')"
        self.__cursor.execute(sql, vars)
        return self.__cursor.fetchall()

    def get_table_fields(self, table, vars=None):
        """获取表字段信息"""
        sql = "SELECT column_name FROM information_schema.COLUMNS WHERE table_schema='public' AND table_name='"+ table +"'"
        self.__cursor.execute(sql, vars)
        fields = []
        for field in self.__cursor.fetchall():
            fields.append(field[0])
        return fields

    def table_metadata(self, table, vars=None):
        """获取表字段信息"""
        sql = "SELECT * FROM information_schema.COLUMNS WHERE table_schema='public' AND table_name='"+ table +"'"
        self.__cursor.execute(sql, vars)
        fields = []
        for field in self.__cursor.fetchall():
            fields.append(field)
        return fields

if __name__ == "__main__":
    pgsqlUtil = PGSQLUtil(host="127.0.0.1", user="root", password="123456", database="xl")
    pgsqlUtil.get_version()
    conn = pgsqlUtil.get_conn()
    ## 查询所有数据库
    databases = pgsqlUtil.list_databases()
    print(type(databases), databases)
    ## 查询当前用户的表
    tables = pgsqlUtil.list_user_tables()
    print(type(tables), tables)
    ## 查询所有表的权限信息
    privileges = pgsqlUtil.list_tables_privileges()
    for privilege in privileges:
        print(privilege)
    ## 查询表数据
    result = pgsqlUtil.execute("SELECT * FROM t_user")
    for i in result:
        print(i)

    # result = pgsqlUtil.get_table_fields("t_user")
    result = pgsqlUtil.table_metadata("t_user")
    for i in result:
        print(i)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/03/06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、环境准备
    • 1、python3安装
    • 2、MongoDB4安装
  • 二、安装驱动
    • 1、psycopg2驱动安装
    • 2、pymogo驱动测试
  • 三、py工具类
    • 1、工具脚本
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文