Can someone please explain how I can get the tables in the current database?
I am using postgresql-8.4 psycopg2.
To list the tables in the current database, you can run the \dt command, in psql : If you want to perform an SQL query instead, run this: SELECT table_name FROM information_schema.
You can fetch data from PostgreSQL using the fetch() method provided by the psycopg2. The Cursor class provides three methods namely fetchall(), fetchmany() and, fetchone() where, The fetchall() method retrieves all the rows in the result set of a query and returns them as list of tuples.
To create a Postgres table in Python, we use the CREATE TABLE SQL statement. This query should be executed after establishing a connection to the database. We also create a cursor object by calling the cursor() method that belongs to the connection object. This cursor object is used to actually execute your commands.
This did the trick for me:
cursor.execute("""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'""") for table in cursor.fetchall(): print(table)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With