Skip to content

Instantly share code, notes, and snippets.

@Hammer2900
Created September 3, 2016 09:34
Show Gist options
  • Select an option

  • Save Hammer2900/b7b2e24558609864a64b23cf54fde62e to your computer and use it in GitHub Desktop.

Select an option

Save Hammer2900/b7b2e24558609864a64b23cf54fde62e to your computer and use it in GitHub Desktop.
Create postgres db and delete from python script.
#!/usr/bin/python
# -*- coding: utf-8 -*-
from psycopg2 import connect
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
class PostgresDbHelper(object):
def __init__(self, host, user, password, dbname):
self.host = host
self.user = user
self.password = password
self.db_name = dbname
self.con = None
self.cursor = None
self._connect()
def _connect(self):
self.con = connect(user=self.user, host=self.host, password=self.password)
self.con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
self.cursor = self.con.cursor()
def _exec(self, command):
self.cursor.execute(command)
def _close(self):
self.cursor.close()
self.con.close()
def create_db(self):
self._exec('CREATE DATABASE {}'.format(self.db_name))
def delete_db(self):
self._exec('DROP DATABASE {}'.format(self.db_name))
def delete_create_db(self):
self.delete_db()
self.create_db()
if __name__ == '__main__':
a = PostgresDbHelper(host='127.0.0.1', user='postgres', password='', dbname='hotel')
# a.create_db()
# a.delete_db()
a.delete_create_db()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment