Created
November 20, 2019 17:21
-
-
Save edgardo001/b62f74b2b1fc8a03ec31cd26f8f96097 to your computer and use it in GitHub Desktop.
Ejemplo básico de conexión a postgres con python sobre contenedores docker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# docker run --name some-postgres -p 5432:5432 -e POSTGRES_PASSWORD=postgres -tid postgres:12.0 | |
# docker run -v C:\Users\Datasoft\Desktop\py:/script --rm python:3.7 bash -c "pip install psycopg2 && python /script/app.py" | |
import psycopg2 | |
try: | |
connection = psycopg2.connect(user = "postgres", | |
password = "postgres", | |
host = "192.168.1.40", | |
port = "5432", | |
database = "postgres") | |
cursor = connection.cursor() | |
# Print PostgreSQL Connection properties | |
print ( connection.get_dsn_parameters(),"\n") | |
# Print PostgreSQL version | |
cursor.execute("SELECT version();") | |
record = cursor.fetchone() | |
print("You are connected to - ", record,"\n") | |
except (Exception, psycopg2.Error) as error : | |
print ("Error while connecting to PostgreSQL", error) | |
finally: | |
#closing database connection. | |
if(connection): | |
cursor.close() | |
connection.close() | |
print("PostgreSQL connection is closed") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment