%pwd
'/Users/gjanee-local/work/meds213/bren-meds213-class-data/week7'
There are lots of these % Jupyter “magic” commands, a few are Bash equivalents.
Allow you to create a string that spans lines, useful for long queries
Tuples are like lists, but are immutable
1-tuple has weird syntax to avoid interpretation as parenthesized expression
Much more concise than writing a loop
[4, 9, 25, 49]
Each database has its own module, or “driver”. Here we use the sqlite3
module. But all drivers provide the same DB-API interface.
Most RDBMSs: specify network location of database. SQLite: specify filename. If file doesn’t exist, a new database is created.
Got a connection, now need a cursor. Can use same cursor for multiple sequential queries. Can have multiple cursors open at once.
<sqlite3.Cursor at 0x112680d40>
Get all results. Get back list of tuples. Tuple element order corresponds to columns. Notice database types carry over to Python. NULL maps to None.
[('14HPE1', None, None),
('11eaba', None, None),
('11eabaagc01', 6.0, 'float'),
('11eabaagv01', 3.0, 'float'),
('11eababbc02', 4.0, 'float'),
('11eababsv01', 2.0, 'float'),
('11eabaduh01', 2.0, 'float'),
('11eabaduv01', 5.0, 'float'),
('11eabarpc01', 4.0, 'float'),
('11eabarpc02', 4.0, 'float')]
The cursor doesn’t hold on to results, it’s just a means of retrieving them one time.
If just one column, still get tuples back.
[('04coatapg01',),
('04coatapg02',),
('04coatapj01',),
('04coatapj02',),
('04coatapp01',),
('04coatapp02',),
('04coatapp03',),
('04coatbbg01',),
('04coatbbg02',),
('04coatbbg03',)]
['04coatapg01',
'04coatapg02',
'04coatapj01',
'04coatapj02',
'04coatapp01',
'04coatapp02',
'04coatapp03',
'04coatbbg01',
'04coatbbg02',
'04coatbbg03']
If only one row coming back, convenient to use fetchone()
BTW, if you want to get help on things in Python, ask for help on a variable, will get back help on that variable’s type.
Can use cursor as iterator. Technique for large returns, more efficient than fetchall()
.
got nest ID 04coatapg01
got nest ID 04coatapg02
got nest ID 04coatapj01
got nest ID 04coatapj02
got nest ID 04coatapp01
got nest ID 04coatapp02
got nest ID 04coatapp03
got nest ID 04coatbbg01
got nest ID 04coatbbg02
got nest ID 04coatbbg03
Same, using new-style interpolation using f"..."
strings.
got nest ID 04coatapg01
got nest ID 04coatapg02
got nest ID 04coatapj01
got nest ID 04coatapj02
got nest ID 04coatapp01
got nest ID 04coatapp02
got nest ID 04coatapp03
got nest ID 04coatbbg01
got nest ID 04coatbbg02
got nest ID 04coatbbg03
<sqlite3.Cursor at 0x112680d40>
No return in this case. Note that temp tables are local to the session, not globally visible.
<sqlite3.Cursor at 0x112680d40>
This table is now visible.