Created
June 23, 2021 16:10
-
-
Save apoorvalal/9e2235f7fb8260bf694bdec11f34d46d to your computer and use it in GitHub Desktop.
example of sqlite <> pandas interop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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