Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing the connection of Postgres-DB

I would like to put a button on the GUI if the software connects to a specific Postgre-DB. I wrote a small test-function: if it can connect to the DB it returns True, if not it returns False.

The code works, but there is an issue: if there is no connection (I just pull out the internet cable, nothing else changes), it simply takes too much time. Could you help me to make the code faster if there is no connection?

Here is my simple test-function:

import psycopg2

def postgres_test():

    try:
        conn = psycopg2.connect("dbname='mydb' user='myuser' host='my_ip' password='mypassword'")
        conn.close()
        return True
    except:
        return False
like image 463
picibucor Avatar asked Jan 30 '17 15:01

picibucor


People also ask

How do I connect to PostgreSQL connection?

The default username for postgres is postgres. (If you are using Advanced Server it is enterprisedb.) On a Mac or Windows, you are able to connect to the default instance by simply hitting enter at the shell or command prompt when trying to run psql and keying in the password.

How do I check my PostgreSQL database?

Use \l or \l+ in psql to show all databases in the current PostgreSQL server. Use the SELECT statement to query data from the pg_database to get all databases.

How can I tell if postgres is running on localhost?

Alternatively you can just "SELECT 1" with psql, and check output: =$ psql -h 127.0. 0.


2 Answers

Thanks for the comments. And yes, it was timeout related.

Here is my faster code:

import psycopg2

def postgres_test():

    try:
        conn = psycopg2.connect("dbname='mydb' user='myuser' host='my_ip' password='mypassword' connect_timeout=1 ")
        conn.close()
        return True
    except:
        return False
like image 145
picibucor Avatar answered Oct 09 '22 15:10

picibucor


For test postgres connection with python first you have to install this package :

pip install psycopg2-binary

and try this code :

import psycopg2

conn = psycopg2.connect(dbname="db_name",
                        user="user_name",
                        host="127.0.0.1",
                        password="******",
                        port="5432")
cursor = conn.cursor()
cursor.execute('SELECT * FROM information_schema.tables')
rows = cursor.fetchall()
for table in rows:
    print(table)
conn.close()
like image 20
hassanzadeh.sd Avatar answered Oct 09 '22 15:10

hassanzadeh.sd