I am developing a CRUD in Python, which will be useful for a project. However, I want to connect the database that I currently have created in PostgreSQL to a kind of online server or online DB, so that in case there is loss of information, it is not necessary to make a recurring backup, but to have all information online or make my computer work as a server. How can I do it?
CodePudding user response:
Okay, first you'll want to the install psycopg2 with pip by doing, pip install psycopg2 or use pip3 then you'll want to try an example such as.
from psycopg2 import Error
try:
# Connect to an existing database
connection = psycopg2.connect(user="postgres",
password="pynative@#29",
host="127.0.0.1",
port="5432",
database="postgres_db")
# Create a cursor to perform database operations
cursor = connection.cursor()
# Print PostgreSQL details
print("PostgreSQL server information")
print(connection.get_dsn_parameters(), "\n")
# Executing a SQL query
cursor.execute("SELECT version();")
# Fetch result
record = cursor.fetchone()
print("You are connected to - ", record, "\n")
except (Exception, Error) as error:
print("Error while connecting to PostgreSQL", error)
finally:
if (connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
CodePudding user response:
You might want to try the psycopg2 library. Psycopg is a PostgreSQL adapter for the Python programming language. It implements PEP 249 with many extensions.
Here is a link: https://pynative.com/python-postgresql-tutorial/