Bản quyền thuộc về TITV.vn,
vui lòng không đăng tải lại nội dung từ trang này.
Video giải thích chi tiết
Nội dung chi tiết
In [9]:
# Cài đặt thư viện
# !pip install pysqlite3
# Import thư viện
import sqlite3
# Kết nối đến cơ sở dữ liệu bằng đường dẫn
path = "C:/Users/Windows/OneDrive/Youtube News/Python/data/csdl.db"
connection = sqlite3.connect(path)
print(connection)
# Ngắt kết nối
# connection.close()
<sqlite3.Connection object at 0x000001F88A42FB70>
In [10]:
# Tạo đối tượng cursor
cursor = connection.cursor()
# Tạo câu lệnh SQL
sql = "SELECT * FROM sinhvien"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
cursor.close()
[('02', 'Nguyen Van A', 6.0), ('01', 'TITV', 11.0), ('03', 'Le Nhat Tung', 8.0)]
In [15]:
# Tạo đối tượng cursor
cursor = connection.cursor()
# Tạo câu lệnh SQL
sql = "SELECT * FROM sinhvien WHERE sinhvien.diemtb>=8"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
cursor.close()
[('01', 'TITV', 11.0), ('03', 'Le Nhat Tung', 8.0), ('06', 'Do My Uyen', 9.0)]
In [17]:
# Tạo đối tượng cursor
cursor = connection.cursor()
# Tạo câu lệnh SQL
sql = "INSERT INTO sinhvien(masv, hovaten, diemtb) VALUES ('07', 'Do My Uyen', 9)"
cursor.execute(sql)
connection.commit()
cursor.close()
#result = cursor.fetchall()
#print(result)
--------------------------------------------------------------------------- IntegrityError Traceback (most recent call last) Input In [17], in <cell line: 6>() 4 # Tạo câu lệnh SQL 5 sql = "INSERT INTO sinhvien(masv, hovaten, diemtb) VALUES ('07', 'Do My Uyen', 9)" ----> 6 cursor.execute(sql) 7 connection.commit() 8 cursor.close() IntegrityError: UNIQUE constraint failed: sinhvien.masv
In [18]:
# Tạo đối tượng cursor
cursor = connection.cursor()
# Tạo câu lệnh SQL
sql = "UPDATE sinhvien set diemtb=diemtb+1"
cursor.execute(sql)
connection.commit()
cursor.close()
In [19]:
# Tạo đối tượng cursor
cursor = connection.cursor()
# Tạo câu lệnh SQL
sql = "DELETE FROM sinhvien WHERE diemtb>10"
cursor.execute(sql)
connection.commit()
cursor.close()
In [21]:
def printAll(result):
for item in result:
print(item)
In [23]:
# Tạo đối tượng cursor
cursor = connection.cursor()
# Tạo câu lệnh SQL
sql = "SELECT * FROM sinhvien ORDER BY masv DESC"
cursor.execute(sql)
result = cursor.fetchall()
cursor.close()
# In dữ liệu
printAll(result)
('07', 'Do My Uyen', 10.0) ('06', 'Do My Uyen', 10.0) ('03', 'Le Nhat Tung', 9.0) ('02', 'Nguyen Van A', 7.0)
In [ ]:
Không có nhận xét nào:
Đăng nhận xét