Python script query to GCP postgresql db from local machine

0 votes
I have a GCP workspace, complete with a Postgresql database. On a frequent basis, I need to insert and/or select rows from the db. I've been searching for a python script that will (A) connect to GCP, then (B) connect to the db, then (C) query a specific table. I'd prefer not to hard code my credentials if possible, that way I could share this script with others on my team, and provided that they were authorized users, it would run without any hiccups.

Does anyone have such a script?
Mar 7, 2022 in GCP by Rahul
• 2,080 points
2,067 views

1 answer to this question.

0 votes

Using the Cloud SQL Python connector you can run a script that looks something like this 

import os
from google.cloud.sql.connector import connector

conn = connector.connect(
    os.getenv("INSTANCE_CONNECTION_NAME"),
    "pg8000",
    user=os.getenv("DB_USER"),
    password=os.getenv("DB_PASSWORD"),
    db=os.getenv("DB_NAME")
)

cursor = conn.cursor()
cursor.execute("SELECT * from my_table")

result = cursor.fetchall()

for row in result:
    print(row)

answered Mar 8, 2022 by Korak
• 5,820 points

Related Questions In GCP

0 votes
2 answers

How to transfer files to GCP VM from local system?

gcloud compute scp localpath vm_instance_name:instance/path READ MORE

answered Oct 27, 2020 in GCP by anonymous
6,070 views
–1 vote
1 answer

How to copy files between Cloud Shell and the local machine in GCP?

Hi@akhtar, You can copy files from the remote ...READ MORE

answered Nov 9, 2020 in GCP by MD
• 95,460 points
9,378 views
0 votes
2 answers

How to install gcp in Python?

If you're accessing BigQuery in python, you ...READ MORE

answered Aug 20, 2018 in GCP by Priyaj
• 58,100 points
1,659 views
+1 vote
1 answer

How do I deploy a cloud function from my local machine?

You can do this using the gcloud command-line tool, ...READ MORE

answered Oct 23, 2019 in GCP by Sirajul
• 59,230 points
907 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
+2 votes
1 answer

How to create a project from GCP Cloud Shell?

Hi@akhtar, GCP shell has a command named gcloud. ...READ MORE

answered Aug 23, 2020 in GCP by MD
• 95,460 points
1,923 views
0 votes
1 answer

How to send email to AWS SES from GCP vm instance

Use port 587. As per AWS SES ...READ MORE

answered Mar 4, 2022 in GCP by Korak
• 5,820 points
962 views
0 votes
1 answer

Google cloud: How to list all service-accounts from all Projects in GCP

Your code sample suggests you want the ...READ MORE

answered Mar 14, 2022 in GCP by Korak
• 5,820 points
3,974 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP