简体   繁体   中英

How to print each row on a new line using Psycopg2 and Postgresql

I wrote a small Python program using Psycopg2 to query a Postgresql database by firstname or lastname. Everything is working fine other than the formatting if I have multiple entries of the same name. For example, if there is only one "Michael", then it will display properly on one line, however, if there are four people named "Dan", they will display next to each other. I want to make a new line after each person so that the formatting looks proper but I can't get it to do so.

Here is the query I am using:

lname = input("Enter First Name: ").upper()

                    print ("\nFirstName    LastName     Office#            Fax#             Cell#")
                    print ("----------- --------- ---------------  ----------------  ---------------")
                    query = "SELECT rtrim(firstname, ' '), rtrim(lastname, ' '), rtrim(officephone, ' '), rtrim(faxnumber, ' '), rtrim(cellphone, ' ') FROM employees where firstname = '" + str(lname) + "';"
                    cur.execute(query)
                    results = cur.fetchall()
                    print(results)
                    print ("\n")

I can't figure out what to put in my query so that it will go to a new line after each person. Any help would be wonderful!

fetchall() returns a list. You can loop over the list and print the results.

for result in results:
    print(result)

Your call results = cur.fetchall() just puts all the retrieved data into a list. Calling print(results) will not print all the items on separate lines:

>>> b=((1,2,3),(4,5,6))
>>> print(b)
((1, 2, 3), (4, 5, 6))

You need to loop through them:

>>> b=((1,2,3),(4,5,6))
>>> print(b)
((1, 2, 3), (4, 5, 6))
>>> for r in b:
...  print(r)
... 
(1, 2, 3)
(4, 5, 6)

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