SQL: Printing your table

Challenge Code: AS48 (50 Points)

Printing all the records

Again we are going to use a function and again we use the with command for safety. This time we will use a simple SELECT command to pull out the records from our DB. It uses tuples (More info) to pass the data back to Python.

Because we are going to print out multiple rows we use a for loop. It then prints out each row. Now the tricky thing to get your head round is even though it says row, you are actually printing out columns from each row. The command really means print this Row, column [0]. Finally printing the end to let you know that there are no more records.

Printing one record

We start by asking which car you'd like to print out. You could do this by speed or name too, but that's a lot of typing.cur = conn.execute("SELECT id, Name, TopSpeed FROM Cars WHERE id = ?", (PrintCar,))row = cur.fetchone()
print ("ID:",row[0],"Name:",row[1],"Top Speed:",row[2],"mph")The first command now does more than simply pull all the records from the table, the WHERE command matches it. The ? mark allows us to put in a variable of our choice into the SQL command and then the variable is named in brackets. Hint: If you only have 1 variable you still have to put in, I don't know why...

Bonus Validate the input (25 points)

If you can validate the input so that only valid records can be chosen or it doesn't crash when you input something invalid, then you can take an easy 25 bonus points.<<BackNext>>

Powered by Create your own unique website with customizable templates.