Introduction:
It is possible to connect to a remote PostgreSQL database using Python and then use your application to access and manipulate the data wherever you are. Visual Studio supports writing Python code, and using libraries such as psycopg2 to connect the code to the database easily. This architecture can be effectively used to develop applications that will interoperate with a remote or cloud-hosted database.
Body:
Prerequisites: refer my following blogs
{https://community.sap.com/t5/blogs/blogworkflowpage/blog-id/aiblog-board/article-id/1138?prePageCrum...}
{https://community.sap.com/t5/blogs/blogworkflowpage/blog-id/aiblog-board/article-id/1139?prePageCrum...}
{https://community.sap.com/t5/blogs/blogworkflowpage/blog-id/aiblog-board/article-id/1140?prePageCrum...}
Create environment file .env in VScode
Add the Service URL in it
Run pip install -r req.txt
Go to PostgreSQL Database and Click the Query tool
Run
select version() and check the result
Go to Visual Studio -> Create file initialize.py -> Write the following code for the above
That should return the same result received in PostgreSQL admin
import psycopg2
import os
from dotenv import load_dotenv
# Load our connection URL from .env (private file)
load_dotenv()
try:
# Connect to the PostgreSQL database using the connection URL
conn = psycopg2.connect(os.getenv("DB_URL"))
query_sql = 'SELECT VERSION()'
cur = conn.cursor()
cur.execute(query_sql)
version = cur.fetchone()[0]
print(version)
except Exception as e:
print(f"connection failed: {e}")
finally:
if 'conn' in locals():
conn.close()And thus your application connected to remote PostgreSQL database server
Summary:
To connect, the first step will be to install the libraries that are required and then provide the database connection details i.e. the host, port, username and password. Then, you can create the connection using Python code in Visual Studio and run queries. After connecting, you are able to effectively carry out functions such as reading, inserting, updating, and managing data.
##if you found this blog helpful, please consider giving it a like
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
| User | Count |
|---|---|
| 23 | |
| 16 | |
| 14 | |
| 14 | |
| 7 | |
| 6 | |
| 5 | |
| 5 | |
| 4 | |
| 4 |