In [5]:
%load_ext sql
%sql sqlite:///chinook.db
Out[5]:
In [2]:
import sqlite3
In [3]:
db = sqlite3.connect('chinook.db')
In [7]:
def task1():
cursor = db.cursor()
cursor.execute('''
select distinct ar.Name
from tracks t
inner join albums al
on t.albumid = al.albumid
inner join artists ar
on al.artistid = ar.artistid
inner join genres g
on t.genreid = g.genreid
where g.name = 'Rock'
''')
ar = cursor.fetchall()
return [x[0] for x in ar]
In [8]:
task1()
Out[8]:
In [44]:
def task2():
cursor=db.cursor()
cursor.execute('''
DROP TABLE IF EXISTS students''')
cursor.execute('''
CREATE TABLE Students(id INTEGERE PRIMARY KEY, name TEXT, gpa NUMBER(10,2))''')
db.commit()
In [45]:
task2()
Проверим, что таблица создана
In [46]:
%%sql
select *
from students
Out[46]:
Для созданной выше функции реализовть возможность добавления списка студентов вида [['Ivanov', 1.2], ['Petrov', 2.3]]. ID новых студентов должно начинаться с максимального ID в таблице + 1. (Например, если в таблице максимальный ID - 10, то у Петрова должно быть - 11, у Иванова - 12). Функция должна предполагать вставки списка любой ограниченной длины.
Получаем max(id) + 1
In [47]:
%%sql
select coalesce(max(id)+1, 1) as new_id from students
Out[47]:
In [48]:
def task3(l_students):
cursor = db.cursor()
cursor.execute( '''
SELECT COALESCE(MAX(ID)+1, 1) AS new_id FROM students''')
new_id = cursor.fetchone()[0]
for i, student in enumerate(l_students):
cursor.execute('''
INSERT INTO Students(id, name, gpa) VALUES(?,?,?)''', (new_id + i, student[0], student[1]))
db.commit()
In [49]:
task3([['Ivanov', 3.2], ['Petrov', 4.2]])
In [50]:
%%sql
SELECT *
FROM Students
Out[50]:
In [51]:
def task4():
cursor = db.cursor()
cursor.execute('''DROP TABLE IF EXISTS faculties''')
cursor.execute('''CREATE TABLE faculties(fac_id INTEGER PRIMARY KEY, name TEXT)''')
cursor.execute('''ALTER TABLE students ADD fac_id INTEGER REFERENCES faculties(fac_id)''')
db.commit()
In [52]:
task4()
In [53]:
%%sql
select *
from faculties
Out[53]:
In [54]:
%%sql
select *
from Students
Out[54]:
Для начала добавим в таблицу факультетов пару записей
In [55]:
%%sql
INSERT INTO faculties(fac_id, name)
VALUES (1, 'IT'), (2, 'KIB'), (3, 'Math')
Out[55]:
In [56]:
%%sql
select *
from faculties
Out[56]:
In [57]:
a = input('1 {}', '2')
In [79]:
def task5():
cursor = db.cursor()
cursor.execute('Select id, name, gpa from Students')
a = cursor.fetchall()
for x in a:
print("Введите факультет для студента {} с id = {} и gpa = {}".format(x[1], x[0], x[2]))
fac_name = input()
cursor.execute("SELECT fac_id from faculties where name = ?", (fac_name, ))
# Проверяем есть ли такая запись
try:
fac_id = cursor.fetchone()[0]
except TypeError:
continue
cursor.execute("Update students set fac_id = ? where id = ?", (fac_id, x[0],))
db.commit()
In [80]:
task5()
In [81]:
%%sql
SELECT *
FROM students
Out[81]:
In [82]:
task5()
In [83]:
%%sql
SELECT *
FROM Students
Out[83]:
In [84]:
def task6(fac_name, l_id):
cursor = db.cursor()
cursor.execute( '''
SELECT COALESCE(MAX(fac_id)+1, 1) AS new_fac_id FROM faculties''')
new_id = cursor.fetchone()[0]
cursor.execute('''
INSERT INTO faculties(fac_id, name) VALUES(?,?)''', (new_id, fac_name,))
for x in l_id:
cursor.execute('''
Update students set fac_id = ? where id = ?''', (new_id, x, ))
db.commit()
In [86]:
task6('Hist', [1])
In [87]:
%%sql
select *
from students
Out[87]:
In [ ]:
In [ ]: