python 簡單的數據庫 sqlite

'''
練習:
1,建立一個學生成績表 Grades,學號  姓名  成績  名次
CREATE TABLE Grades (num INTEGER PRIMARY KEY,name TEXT,grade INTEGER,rank INTEGER)
2,往表中插入10數據
INSERT IN TO Grades (num,name,grade,rank) VALUES (1,’zhangsan’,398,20)
3,查詢成績大於60分的人的名字
SELECT name,grade FROM grades WHERE grade > 60
4,查詢成績小於60分的人的個數
SELECT COUNT(*) FROM grades WHERE grade < 60
5,把成績小於60分的人的成績修改成60分
UPDATE grades SET grade = 60 WHERE grade < 60
6,刪除全部學號小於100的人的信息
DELETE FROM grades WHERE num < 100
6,查詢姓「張」的人的全部信息
SELECT * FROM grades WHERE name LIKE '張%'
7,查詢全部人的成績,按照成績從高到低排列
SELECT grade FROM grades ORDER BY grade DESC
8,查詢全部人的成績,按照名次從小到大排列
SELECT grade FROM grades ORDER BY rank ASC
'''
import sqlite3
connect = sqlite3.connect('database01.db')
cursor = connect.cursor()
# 插入一張表,學生成績表Grades: num, name;grade;rank
sql = "CREATE TABLE Grades(num INTEGER PRIMARY KEY,name TEXT,grade INTEGER,rank INTEGER)"
#cursor.execute(sql)
# 2 添加數據
sql = "INSERT INTO Grades(num,name,grade,rank) VALUES (10,'王昭君',600,10)"
#cursor.execute(sql)
connect.commit()

# 3 查詢成績大於60 分的人的名字
sql = 'SELECT name,grade FROM Grades WHERE grade> 60'
rs = cursor.execute(sql)
rs = list(rs)
print(rs)
connect.commit()
# 查詢成績小於400 分的人的名字
sql = 'SELECT COUNT(*) FROM Grades WHERE grade<400'
rs = cursor.execute(sql)
rs = list(rs)
print(rs)
connect.commit()
# 5 把成績小於400的成績改成 400
sql = 'UPDATE Grades SET grade = 400 WHERE grade<400'
cursor.execute(sql)
connect.commit()
# 6 刪除學號小於5的人的信息
sql = 'DELETE FROM Grades WHERE num <5'
cursor.execute(sql)
connect.commit()
#7 查找姓 張的人的全部信息
sql = "SELECT * FROM Grades WHERE name like '張%'"
rs = cursor.execute(sql)
for x in rs:
    print(x)
connect.commit()
# 8 查詢全部人的成績,按照成績從高到低排列
sql = 'SELECT name,grade FROM Grades ORDER BY grade DESC'
rs = cursor.execute(sql)
rs = list(rs)
print(rs)
connect.commit()

# 9 查詢全部人的成績,按照名次從小到大排列
sql = 'SELECT name,grade FROM Grades ORDER BY rank ASC'
rs = cursor.execute(sql)
rs = list(rs)

print(rs)
connect.commit()

 

1.建立新表
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)

2.刪除表
drop table tabname

3.查詢:select * from table1 where 範圍

4.插入:insert into 表名(字段名1,字段名2) values(值1,值2)

5.刪除:delete from table1 where 範圍

6.修改:update 表名 set 修改的字段名=修改的字段值 where 範圍

7.查找:select * from table1 where field1 like ’%value1%’ N%匹配以N開頭     %N匹配以N結尾   %N%匹配包含N  
	[a,b]% 以a或b開頭     %[a,b]以a或b結尾

	select * from table1 where field1 like 'z_'以z開頭且匹配以後一個字符

	升序輸出數據記錄
	select * from table_name order by field asc
	降序輸出數據記錄
	select * from table_name order by field desc

9.總數:select count (*) from table_name;