As SQLite is a file based database so we can place one sample database in google drive and then mount the drive to our colab platform. We can connect to SQLite using colab pre installed libraries and use all database management functions.
No need to download or install any software to work with SQLite.
We can create database and then use it from the Colab platform but for easy testing, this sample SQLite database ( my_db.db ) file can be downloaded and placed in your google drive.
Google colab platform to connect to SQLite database using SQL magic extension
%load_ext sql
# we can use the magic extension to connect to our SQLite DB
%sql sqlite:///my_db.db
# use %sql to write an inline SQL command
# use %%sql to write SQL commands in a cell
%%sql
SELECT name FROM sqlite_master WHERE type='table' ;
Output
Done.
name
category
subcategory
student
Structure of the student table
%sql PRAGMA table_info([student]);
Output
* sqlite:///my_db.db
Done.
cid name type notnull dflt_value pk
0 id INTEGER 0 None 1
1 name TEXT 0 None 0
2 class TEXT 0 None 0
3 mark INTEGER 0 None 0
4 gender TEXT 0 None 0
%%sql
SELECT * FROM student LIMIT 0,5
Output
* sqlite:///my_db.db
Done.
id name class mark gender
1 John Deo Four 75 female
2 Max Ruin Three 85 male
3 Arnold Three 55 male
4 Krish Star Four 60 female
5 John Mike Four 60 female
result = %sql SELECT * FROM student LIMIT 0,5;
#result.DataFrame().loc[0, 'name'] # first name only
result.DataFrame().loc[:,'name'] # all names
Connecting using SQLAlchemy
Use the copied path in below code to connect.
from sqlalchemy import create_engine
my_conn=create_engine("sqlite:////content/drive/MyDrive/my_db/my_db.db")
or by giving same path
my_conn=create_engine("sqlite:////my_db.db")
Database connection is ready, we will check by using this code to list the tables available in our sample database.
r_set=my_conn.execute('''select name from sqlite_master
where type = 'table' ''')
for row in r_set:
print(row)
Output is here ( with sample tables )
('category',)
('subcategory',)
('student',)
Or to get all the records from the student ( sample ) table.
r_set=my_conn.execute('''SELECT * from student''');
for row in r_set:
print(row)
Connecting using sqlite3
# download my_db.db SQLite Database from plus2net.com
!wget https://www.plus2net.com/python/download/my_db.db
import sqlite3
my_conn = sqlite3.connect('my_db.db') # connect to db
query="SELECT * FROM student LIMIT 0,5" # sql
my_data=list(my_conn.execute(query)) # rows of data as list
print(my_data)