Problem with the Connection to BD Postgresql with python

2
import psycopg2
class BaseDeDatos:
def _init_(self):
    try:
        self.conexion=psycopg2.connect(
            "host='localhost' port='5432' dbname='Inversiones' 
                          user='postgres' password='xxxxxx'")
        self.conexion.autocommit = True
        self.cursor = self.conexion.cursor()
    except:
        print("No se pudo conectar a la base de datos")
def crearTabla(self):
    crearTablaComando = "CREATE TABLE Pet(name varchar(20)[], age integer 
                                NOT NULL)"
    self.cursor.execute(crearTablaComando)


if __name__=='_Base_de_datos_':
     baseDeDatos=BaseDeDatos()
     baseDeDatos.crearTabla

When I compile, I do not see any error, but when going to postgres, I do not see the new table, and I do not know if it is not connecting to the database or if it is not creating the table. If I do not put the if__name __... I get this error:

self.cursor.execute(crearTablaComando)
AttributeError: 'BaseDeDatos' object has no attribute 'cursor'

help, please. I'm starting in python, so do not be harsh with me :( haha

    
asked by sergeee30 18.02.2018 в 04:12
source

1 answer

2

The problem that I find is that it is __ init __ (two underscores on each side) and not init (with a single underscore of each side as you wrote) is for this reason that the cursor is never created (since the connection is not executed). I did a test and if you change that and you specify correctly the connection data, OK works.

 import psycopg2
 class BaseDeDatos:
    def __init__(self):
      try:

        self.conexion=psycopg2.connect("host='localhost' port='5433' 
                      dbname='Inversiones' user=postgres password=admin123")
        self.conexion.autocommit = True
        self.cursor = self.conexion.cursor()

      except:
         print("No se pudo conectar a la base de datos")
    def crearTabla(self):
        crearTablaComando = "CREATE TABLE Pet(name varchar(20)[], age integer NOT NULL)"
        self.cursor.execute(crearTablaComando)

When you execute it you have to put it to boot or you can also go without the if.

  if __name__=='__main__':
     baseDeDatos=BaseDeDatos()
     baseDeDatos.crearTabla()

Copy my code, change the connection data (and use mine and execute it.) Attach evidence )

    
answered by 18.02.2018 / 05:22
source