问题
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