Introduction to Databases and SQL

Plan

  • open sqlite3 database
  • send a query
  • parse and print the result
  • import from sqlite directly into pandas

In [4]:
import sqlite3
conn = sqlite3.connect('mtcars.sqlite')
c = conn.cursor()

select cars with 4 cylinders


In [5]:
# create and execute our query
cylinders = 4
cursor = c.execute("SELECT * FROM results WHERE cyl = {0}".format(cylinders))

print a list of the results


In [6]:
# fetch a list of the column names
column_names = list(map(lambda x: x[0], cursor.description))

# fetch all rows and map column names onto them
rows = map(lambda x: dict(zip(column_names, x)), cursor.fetchall())

# print the name and MPG for each result
for row in rows:
    print("{name}:\t{mpg}".format(**row))


Datsun 710:	22.8
Merc 240D:	24.4
Merc 230:	22.8
Fiat 128:	32.4
Honda Civic:	30.4
Toyota Corolla:	33.9
Toyota Corona:	21.5
Fiat X1-9:	27.3
Porsche 914-2:	26.0
Lotus Europa:	30.4
Volvo 142E:	21.4

import into pandas


In [7]:
import pandas as pd
df = pd.read_sql_query("SELECT * from results", conn)
print(df.head())


    mpg  cyl   disp   hp  drat     wt   qsec  vs  am  gear  carb  \
0  21.0    6  160.0  110  3.90  2.620  16.46   0   1     4     4   
1  21.0    6  160.0  110  3.90  2.875  17.02   0   1     4     4   
2  22.8    4  108.0   93  3.85  2.320  18.61   1   1     4     1   
3  21.4    6  258.0  110  3.08  3.215  19.44   1   0     3     1   
4  18.7    8  360.0  175  3.15  3.440  17.02   0   0     3     2   

                name  
0          Mazda RX4  
1      Mazda RX4 Wag  
2         Datsun 710  
3     Hornet 4 Drive  
4  Hornet Sportabout  

In [ ]: