All I have, I carry with me: Continuing Database Operations
All I have, I carry with me: Continuing Database Operations
Just doing a few minutes here and there, because I need this to be done. I am so happy that my intermediate Python course is done.
I am also so happy that the advanced modules are so easy. Where have you been all my life.
Maybe something has finally clicked. These are so much easier than the intermediate ones! I can feel my love for the windfarms.
It is stronger than ever. Everything is beating so much stronger in my heart. And all I have, I carry with me.
All I have, I carry with me.
Retrieving Data
When combined with cursor.execute(), .fetchone() will fetch one row of data. It will pull the first row of the data table. .fetchmany() will fetch many data rows - it will return the first set of specified rows.
It will return a list of tuples.
Finally, .fetchall() will fetch every row of data from the data table.
I wrote a big piece of code about this.
Here we are now:
import sqlite3
con = sqlite3.connect("titanic.db")
curs = con.cursor()
# Pull the first row from the titanice data table (print to view output)
one = curs.execute("SELECT * FROM titanic").fetchone()
print(one)
# Pull the first ten rows from the titanice data table (print to view output)
ten = curs.execute("SELECT * FROM titanic").fetchmany(10)
print(ten)
# Pull every row from the titanice data table (print to view output)
all_rows = curs.execute("SELECT * FROM titanic").fetchall()
print(all_rows)
# Pull every row from the titanice data table for those who survived (print to view output)
all_survived = curs.execute('''SELECT * FROM titanic WHERE Survived=1''').fetchall()
print(all_survived)
Thank you
I promised myself I'd do one more, so here we go.
I can't wait to go and sleep for 12 hours omg.
Oh no... it's a big one:
Using Loops with SQLite
Like we used fetch methods, we can also use for loops to retrieve data.
Here is my code:
import sqlite3
con = sqlite3.connect("titanic.db")
curs = con.cursor()
# Pull the Age records from the titanic table using .fetchall() method and save as age
age = curs.execute("SELECT Age FROM titanic;").fetchall()
# for loop that calculates the average
sum = 0
for person in age:
if person[0] < 18:
sum += 1
print(sum)
I want to keep going but I promised myself I'd stop.
I only have one more lesson and then a quiz and a project and then I'm done with this little module.
Comments
Post a Comment