DEV Community

Durga Pokharel
Durga Pokharel

Posted on

Day 33 Of 100DayOfCode: Python Code Using Sqlite Operator

This is my 33 day of #100DaysOfcode and #Python. Today I Revised python data structure from coursera. Completed some assignment. Tried to write some code regarding to that topic. Also continue to learned more about database using python. Create some table using SELECT, UPDATE, JOIN operator.

Below is the code where joined operator is used to join the row of the different table.

Python Code Using Join operator.

In this code at first we importing sqlite3 library. We used the table teacher. We choose the row from Teacher table similarly. We used Department table and choose the row from Department table. And we apply JOIN operator To join the row of Department table and row of teacher table.

import sqlite3

conn = sqlite3.connect('school.sqlite')
cur = conn.cursor()

cur.execute('SELECT * FROM Teacher')
count = 0
print('Teacher:')
for row in cur:
    if count < 5: print(row)
    count = count + 1
print(count, 'rows.')

cur.execute('SELECT * FROM Department')
count = 0
print('Department:')
for row in cur:
    if count < 5: print(row)
    count = count + 1
print(count, 'rows.')

cur.execute('''SELECT * FROM Department JOIN Teacher
            ON Department.code = Teacher.id
            WHERE Teacher.id = 3''')

count = 0
print('Connections for id = 3:')
for row in cur:
    if count < 5: print(row)
    count = count + 1
print(count, 'rows.')

cur.close()

Enter fullscreen mode Exit fullscreen mode

When this code is run I got following output

Teacher:
(1, 'Tulsi prased Nepal', 2024, 'Male', 'Mathematics')
(2, 'Viper Kaka', 2055, 'Male', 'It')
(3, 'Naran Gautum', 2044, 'Male', 'Physics')
(4, 'Bishnu Gyawali', 2045, 'Male', 'Statictits')
(5, 'Sarmila Pandey', 2053, 'Female', 'Chemistry')
11 rows.
Department:
('001', 'Mathematics')
('002', 'Physics')
('003', 'Chemistry')
('004', 'Biology')
('005', 'Zoology')
10 rows.
Connections for id = 3:
('003', 'Chemistry', 3, 'Naran Gautum', 2044, 'Male', 'Physics')
1 rows.
Enter fullscreen mode Exit fullscreen mode

Day 33 of #100DaysOfCode and #Python
* More About Database Using Python .
* Code Using Join Operator.#100DaysOfCode ,#CodeNewbies ,#Python pic.twitter.com/DkoK3N8O8G

— Durga Pokharel (@mathdurga) January 26, 2021

Top comments (0)