Testing the connection of Postgres-DB
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC P Beethoven - Piano Sonata No 2 in A
--
Chapters
00:00 Question
00:51 Accepted answer (Score 6)
01:12 Answer 2 (Score 3)
01:43 Thank you
--
Full question
https://stackoverflow.com/questions/4193...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #postgresql #psycopg2
#avk47
--
Track title: CC P Beethoven - Piano Sonata No 2 in A
--
Chapters
00:00 Question
00:51 Accepted answer (Score 6)
01:12 Answer 2 (Score 3)
01:43 Thank you
--
Full question
https://stackoverflow.com/questions/4193...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #postgresql #psycopg2
#avk47
ACCEPTED ANSWER
Score 7
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
ANSWER 2
Score 5
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()