Example 15.1

Python code

import pandas as pd
import sqlite3

# Load a dataframe
url = "https://cssbook.net/d/gun-polls.csv"
d = pd.read_csv(url)

# connecting  to a SQLite database
conn = sqlite3.connect("mydb.db")
# store the df as table "gunpolls" in the database
d.to_sql("gunpolls", con=conn)

# run a query on the SQLite database
sql = """SELECT support, pollster 
         FROM gunpolls LIMIT 5;"""
d2 = pd.read_sql_query(sql, conn)
# close connection
conn.close()
d2

R code

library(tidyverse)
library(RSQLite)

# Load a dataframe
url = "https://cssbook.net/d/gun-polls.csv"
d = read_csv(url)

# connecting  to a SQLite database
mydb = dbConnect(RSQLite::SQLite(), "mydb.sqlite")
# store the df as table "gunpolls" in the database
#dbWriteTable(mydb, "gunpolls", d)

# run a query on the SQLite database
sql = "SELECT support, pollster 
       FROM gunpolls LIMIT 5;"
d2 = dbGetQuery(mydb, sql)
d2
# close connection
dbDisconnect(mydb)