Explore interactive code cells, transfer data between SQLite and Excel files using Pandas, and test SQLAlchemy 2.0+ context manager connections directly in Google Colab.
View on GitHub
import sqlite3
my_path = 'G:\My Drive\testing\my_db\my_db.db' # update path
my_conn = sqlite3.connect(my_path)
print("Connected to database successfully")
Using SQLAlchemy (2.0+ Context Manager Standard)
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
my_path = 'G:\My Drive\testing\my_db\my_db.db' # update path
my_conn = create_engine("sqlite:///" + my_path)
We will use read_sql() to create the DataFrame by using the query.from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
import pandas as pd
my_path = 'G:\My Drive\testing\my_db\my_db.db'
my_conn = create_engine("sqlite:///" + my_path)
try:
q = "SELECT * FROM student" # query to collect record
with my_conn.connect() as connection:
df = pd.read_sql(q, connection, index_col='id') # create DataFrame
print(df.head()) # Print top 5 rows as sample
df.to_excel('D:\student.xlsx') # create the excel file
except SQLAlchemyError as e:
print(e)
else:
print("DataFrame created successfully..")

from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
import pandas as pd
my_path = 'G:\My Drive\testing\my_db\my_db.db' # update path
my_conn = create_engine("sqlite:///" + my_path) # connection object
try:
df = pd.read_excel('D:\student.xlsx') # create DataFrame by reading Excel
print(df.head()) # Print top 5 rows as sample
with my_conn.begin() as connection:
df.to_sql(con=connection, name='student3', if_exists='append') # create table
except SQLAlchemyError as e:
print(e)
else: # show all records to confirm
with my_conn.connect() as connection:
r_set = connection.execute(text('SELECT * FROM student3'))
for row in r_set:
print(row)
SQLite to Excel using Colab platform
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.