Artificial Intelligence Blogs Posts
cancel
Showing results for 
Search instead for 
Did you mean: 
Trupti81
Explorer
0 Likes
140

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

 

Trupti81_4-1777865065519.png

 

Run pip install -r req.txt

 

Trupti81_0-1777864938014.png

Go to PostgreSQL Database and Click the Query tool

 

 

Trupti81_1-1777864969605.png

Run 

select version() and check the result

 

Trupti81_2-1777864969605.png

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

Trupti81_5-1777865182938.png

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