简体   繁体   中英

Get data from Heroku Postgres externally using database url in python

I am trying to access my Heroku Database from an external application. I have the link to the postgres url for my Heroku app, but I am unable to get the data from the database. I have tried the following:

import psycopg2
import os

DB_URI=os.environ.get('DATABASE_URL') or 'sqlite:///'+os.path.join(basedir, 'app.db')

conn=psycopg2.connect(DB_URI)
cur=conn.cursor()
cur.execute("SELECT * FROM USER;")

print(cur.fetchone())

But I get a random name instead of the data I need. Is there any way to solve this problem?

This is the correct way to connect to the DB.

Your connection with the Postgres DB is OK, because psycopg2 would raise OperationalError or the like otherwise.

The "random name" you're getting with SELECT * FROM USER is in fact your Postgres username (which Heroku defines for you), and that's exactly what you asked by performing this query.

You have to write a correct SQL query, which depends of you needs.

For exemple, if you have your data stored in a table called myapp_mytable , cur.execute("""select * from myapp_mytable""") will work like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM