Psycopg2 Python and PostgreSQL
If I am given a text file called test.txt that contains the name of various tables
*test.txt and its contents*
testTable
Students
Teachers
Using Psycopg2 (Python and PostgreSQL), how would you read the text file and output the number of rows each table contains?
You can do this task as two parts.
Part 1 : Read the table names from file
Part 2 : find the row count in each table
code :
For part 1 : open the file and read the content to a variable:
f = open("test.txt")
data = f.read().split("\n")
f.close()
Now the variable data contains the list of table names.
Par2 : As you dosent specify the database name, I hope you had already made a connection to the database.
and let variable "conn" be the conncetion reference to the database.
Then create a cursor object using that conn variable
as
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
for i in data:
querry = "SELECT * from "+i
#Retrieving data
cursor.execute(querry)
#Fetching all row from the table
result = cursor.fetchall();
print("The table named ",i," contains ",len(result), + " rows.")
#Closing the connection
conn.close()
Get Answers For Free
Most questions answered within 1 hours.