python操作postgresql批量删表

最近需要在pg库需要删除大量的表,之前采取的方式是进入postgresql,在Linux命令行使用pgsql,然后在交互命令中使用“drop table test_table”语句批量删表;
这样感觉效率好低,为此采用了python连接pg库,然后批量删表。

  1. 先导入必要的包
import pandas as pd
import psycopg2
import logging
logger = logging,getLogger('main')
  1. 提供ip地址,用户名,库名,密码等,然后连接数据库
def get_database_conn():
    try:
        conn = psycopg2.connect(database = "testdb",user = "postgres",
                                password = '*****', host = 'localhost', port = '5432')
        print("database e connection success!")
    except psycopg2.operationalError as e:       
        conn = None
        logger.info("database connection error!\n{0}.format(e))
    return conn
  1. 获取testdb这个库下面所有的表名
 def get_tablename():
      '''获取库下面所有的表名'''
      schemaname = 'public'
      df_tables = pd.read_sql_query("select * from pg_tables where schemaname = {0}".format(schemaname), con = conn)
      tables = df_tables['tablename']
      
      return tables
  1. 将获取到的表名传到需要执行的sql语句里面做一个变量替换
def drop_table():
    '''每次需要更改时候只需要修改更改执行的sql语句'''
    #建立数据库连接
    conn = get_database_conn()
    #打开游标
    cur = conn.cursor()
    
    tables = get_tablename()
    print"get tablename successfully")

    try:
        for table in tables:
            sql = ('drop table if exists %s;'% table)
            cur.execute(sql)
            print(sql, "->Table deleted successfully")
        
        #确认提交  
        conn.commit()
    
    except Exception as e:
        logger.exception('database execute sql error!{0}'.format(e))
        
        #返回一个空列表
        return []
    finally:
        cur.close()
        conn.close()

你可能感兴趣的:(python)