Skip to content

Instantly share code, notes, and snippets.

@apoorvalal
Created June 23, 2021 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apoorvalal/9e2235f7fb8260bf694bdec11f34d46d to your computer and use it in GitHub Desktop.
Save apoorvalal/9e2235f7fb8260bf694bdec11f34d46d to your computer and use it in GitHub Desktop.
example of sqlite <> pandas interop
import pandas as pd
import sqlite3
# %%
Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
'Price': [22000,25000,27000,35000]
}
df = pd.DataFrame(Cars, columns= ['Brand', 'Price'])
print (df)
# %% create database
conn = sqlite3.connect('TestDB1.db'); c = conn.cursor()
# %% create table
c.execute('CREATE TABLE CARS (Brand text, Price number)')
conn.commit()
# %% write to db
df.to_sql('CARS', conn, if_exists='replace', index = False)
# %% read from sqlite
dbpath = "TestDB1.db"
cnx = sqlite3.connect(dbpath)
cursor = cnx.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
# %%
df = pd.read_sql("SELECT * FROM CARS", cnx)
df.info()
# %%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment