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
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.
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.
Alternatively you can just "SELECT 1" with psql, and check output: =$ psql -h 127.0. 0.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With