Last active
April 4, 2020 19:08
-
-
Save VycktorStark/124c79a742f68a03ed365c8dc3ee24b2 to your computer and use it in GitHub Desktop.
Database using psycopg2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__all__ = ['Conexao'] | |
import psycopg2 | |
class Conexao(object): | |
def __init__(self, _host, db, _user, pwd, port): | |
self._db = psycopg2.connect(host=_host, database=db, user=_user, password=pwd, port=port) | |
def execute(self, sql=None): #execute condition in database | |
try: | |
db = self._db | |
cursor = db.cursor() | |
cursor.execute(sql) | |
db.commit() | |
db.close() | |
res = "Ok" | |
except Exception as error: | |
res = error | |
return res | |
def create(self, table=None, values=None): #create table in database | |
sql = "create table {} ({})". format(table, values) | |
r = self.execute(sql) | |
return | |
def insert(self, table=None, values=None): #insert values in database | |
sql = "insert into {} values ({})". format(table, values) | |
r = self.execute(sql) | |
return | |
def update(self, table=None, upg=None, where_=None): #update condition in database | |
sql = "update {} set {} where {}".format(table, upg, where_) | |
r = self.execute(sql) | |
return r | |
def consult(self, key=None, table=None, where_=None): | |
resp=None | |
sql = "select {} from {}".format(key, table) | |
if (where_ is None) == False: | |
sql = "{} where {}".format(sql, where_) | |
try: | |
cursor = self._db.cursor() | |
cursor.execute(sql) | |
resp = cursor.fetchall() | |
except Exception as error: | |
resp="404 - NOT FOUND\n{}".format(error) | |
self._db.close() | |
return resp | |
def next(self, table=None, key=None): | |
sql='select max({}) from {}'.format(key, table) | |
rs = self.consult(sql) | |
pk = rs[0][0] | |
return pk+1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FIXBUG: