python使用psycopg2管理postgres 连接数据库 创建ROLE或USER 创建/删除数据库

基于docker的postgres 部署见这篇 https://www.cnblogs.com/xuanmanstein/p/7742647.html

import psycopg2class MyTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        db = '172.19.0.12'
        # root用户 先连到默认数据库
        connection_parameters = {
            'host': db,
            'database': 'postgres',
            'user': 'postgres',
            'password': 'example'
        }
        cls.conn = psycopg2.connect(**connection_parameters)
        cls.conn.autocommit = True

创建ROLE或USER

必须用连接其他数据库的其他用户,才能删除和创建别的用户,典型如默认用户postgres 连接到postgres,然后删除创建别的用户,和别的数据库

    def test_create_user(self):
        #创建用户
        name = 'stavka'
        pwd = '1111'
        SQL = f'''
                  DROP ROLE IF EXISTS {name};
                  CREATE ROLE {name};
                  ALTER ROLE {name} ENCRYPTED PASSWORD '{pwd}';
                  ALTER ROLE {name} LOGIN CREATEDB CREATEROLE;
               '''
        # 执行
        with self.conn.cursor() as cursor:
            cursor.execute(SQL)

 先删除(如果存在),再创建,再设置密码,最后设置各种权限

创建/删除数据库

为了使用postgis,在docker镜像建立的时候,已经1个template_postgis数据库,安装了各种extention,

然后就可以用它作为模板,来创建新数据库


self.conn.autocommit = True
self.conn.set_isolation_level(0)
with self.conn.cursor() as cur:
    cur.execute(f'''DROP DATABASE IF EXISTS {db_name};''')
    cur.execute(f'''CREATE DATABASE {db_name} OWNER {role_name} TEMPLATE template_postgis;''')

如果pgAdmin4里已经连接了 template 和删除的目标数据库中任意1个,则会报错

psycopg2.errors.ObjectInUse: database "XXX" is being accessed by other users
DETAIL: There is 1 other session using the database.