How to connect to PostrGreSQL with a python script?

0

I want to connect to a database with a Python script but I have a problem doing it. I use Psycopg but it returns an exception. Here is the script:

#!/usr/bin/python
#
# Pequeno script para connectarme a PostgreSQL con Pyscopg
#

import psycopg2

try:
        conn = psycopg2.connect("dbname='eclipse' user='swiper' host='el host...'")

except:
        print "no estoy capaz connectarme"

Here is what the terminal sends me:

:~$ ./testPostreSQLPython.py 
I am unable to connect to the database

I have a url too ... Maybe it's better to do it? But I do not think I can use it with Psycopg.

    
asked by ThePassenger 18.05.2017 в 11:58
source

1 answer

0

I understand that you are trying to connect to a database on a remote server. The first thing you should try is to get some more information about the error, try the following to see if it gives any clue:

import traceback
import psycopg2

try:
    conn = psycopg2.connect("dbname='eclipse' user='swiper' host='el host...'")

except psycopg2.Error as e:
    print "I am unable to connect to the database"
    print e
    print e.pgcode
    print e.pgerror
    print traceback.format_exc()

On the other hand, you should not have any problem connecting with something like:

import traceback
import psycopg2

params = {
  'database': 'nombre_db',
  'user': 'usuario',
  'password': 'contraseña',
  'host': '333.333.333.333',
  'port': '3333'
}

try:
    conn = psycopg2.connect(**params)

except psycopg2.Error as e:
    print "I am unable to connect to the database"
    print e
    print e.pgcode
    print e.pgerror
    print traceback.format_exc()

As of PostgreSQL 9.2 I believe that if you accept the use of the URL.

You should check that you have authorization in the database to access remotely and whether or not SSL is required. Try connecting to the terminal using psql to see that it is not something from psycopg2:

psql --dbname=nombre_db --username=usario --password=contraseña --host=333.333.333.333 --port=3333
    
answered by 18.05.2017 / 13:03
source