Print out the result of sqlite database query with a format

荒凉一梦 提交于 2020-01-24 19:31:08

问题


I have this student db with four columns: first_name, middle_name, last_name, school, birth_year. I have successfully read the content of the db using SELECT statement, but here's where I got stuck at:

How do I print the query result with the format like this: first_name middle_name(if available) last_name was born in birth_year? So for every row in the query the intended result should do this: Aida Blue was born in 1985.

For now if I run print(all_rows) the code will print the query result like this: [{'first_name':'Aida', 'middle_name': None, 'last_name': 'Blue', 'school': 'Washington', 'birth_year': 1981}, {...}, ....]

Below is my code attempt at such problem:

db = cs.SQL("sqlite:///students.db")

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: python student_school.py school")
        sys.exit()
    else:
        school = str(sys.argv[1])
        all_rows = db.execute("SELECT * FROM students WHERE school=?", school)
        first = all_rows[:][0] #I want to pick up the first col
        middle = all_rows[:][1] #if value <> None?
        last= all_rows[:][2]
        birth_year = all_rows[:][4]
        print(first_name, " " , middle_name, " ", last_name, "was born in ", birth_year \n)

Can anyone please advice? Thank you!


回答1:


  • Your all_rows variable list of dictionaries. Each dict representing a student record.
  • You can write a for loop to iterate over it and print each one.
  • Also in print statement when you write ',' it will automatically put seperater to (single space). There is no need to explicitly write " ". Same with \n there is no need to explicitly write '\n'. Read more here https://docs.python.org/3/library/functions.html#print.
db = cs.SQL("sqlite:///students.db")

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: python student_school.py school")
        sys.exit()
    else:
        school = str(sys.argv[1])
        all_rows = db.execute("SELECT * FROM students WHERE school=?", school)
        for student in all_rows:
            print(student['first_name'], student['middle_name'] if student['middle_name'] else '', student['last_name'], "was born in", student['birth_year'])


来源:https://stackoverflow.com/questions/59816989/print-out-the-result-of-sqlite-database-query-with-a-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!