OK. 按照这个规则来看. 每一条数据对应的就是一个人的信息.
创建表有两种方案:
create table table_student(
sno int(10) primary key auto_increment,
sname varchar(50) not null,
sbirthday date not null,
saddress varchar(255),
sphone varchar(12),
class_name varchar(50),
)
数据类型 | 说明 |
---|---|
int | 整数 |
double | 小数 |
varchar | 字符串 |
date | 时间(年月日) |
datetime | 时间(年月日时分秒) |
text | 文本 |
数据类型 | 说明 |
---|---|
primary key | 主键, 全表唯一值 |
auto_increment | 主键自增. |
not null | 不可以为空. |
null | 可以为空 |
default | 设置默认值 |
ALTER TABLE table_name ADD COLUMN column_name datatype
ALTER TABLE table_name DROP COLUMN column_name
ALTER TABLE table_name
MODIFY COLUMN column_name datatype
ALTER TABLE table_name RENAME TO new_name
INSERT INTO table_name(col1, col2, ccol3...) values (val1,val2,val3)
INSERT INTO STUDENT(sname, sbirthday, saddress, sage, class_name) values ('周杰伦', '2020-01-02', "北京市昌平区", 18, "二班");
DELETE FROM table_name where 条件语句
DELETE FROM STUDENT where sno = 1 ;
UPDATE table_name SET col1 = val1, col2 = val2... where 条件语句
UPDATE STUDENT SET SNAME = '王力宏' where sno = 1;
SELECT *|col1, col2, col3 FROM table_name where_条件
SELECT * FROM STUDENT;
SELECT sname, sage FROM STUDENT;
select * from student where sno = 1;
select * from student where sage > 20;
select * from student where sage >= 20 and sage <= 40;
select * from student where sage between 20 and 40 ;
select * from student where sname like '张%';
select * from table_name group by col_name
select avg(sage), class_name from STUDENT group by class_name;
select min(sage), class_name from STUDENT group by class_name;
select max(sage), class_name from STUDENT group by class_name;
select count(*), class_name from STUDENT group by class_name;
select sum(sage), class_name from STUDENT group by class_name;
select avg(sage), class_name from student group by class_name having avg(sage) > 15;
select * from student order by sage asc
select * from student order by sage desc
-- 创建学生表, 课程表, 成绩表
-- 1. 学生表: 学号, 姓名, 性别, 住址等...
-- 2. 课程表: 课程编号, 课程名称, 授课教师等...
-- 3. 学生课程-成绩表: 成绩表编号, 学号, 课程编号, 成绩
create table stu(
sid int primary key auto_increment,
sname varchar(50) not null,
gender int(1),
address varchar(255)
);
create table course(
cid int primary key auto_increment,
cname varchar(50) not null,
teacher varchar(50)
);
create table sc(
sc_id int primary key auto_increment,
s_id int,
c_id int,
score int,
CONSTRAINT FK_SC_STU_S_ID FOREIGN key(s_id) REFERENCES stu(sid),
CONSTRAINT FK_SC_COURSE_C_ID FOREIGN key(c_id) REFERENCES course(cid)
);
在where语句中可以进行另外的一个查询.
例如, 查询选择了"编程"这门课的学生
-- 查询选择了"编程"这门课的学生
-- 先查询编程课程的编号
select cid from course where cname = '编程';
-- 根据cid可以去sc表查询出学生的id
select s_id from sc where c_id = 2;
-- 根据学生ID查询学生信息
select * from stu where sid in (1,2,3,4,5,6);
-- 把上面的sql穿起来
select * from stu where sid in (
select s_id from sc where c_id in (
select cid from course where cname = '编程'
)
);
-- 查询课程名称为“编程”,且分数低于60的学生姓名和分数
select stu.sname, sc.score from stu, sc where stu.sid = sc.s_id and sc.score < 60 and sc.c_id in (
select cid from course where cname = '编程'
)
把多个表格通过join的方式合并在一起进行条件检索。
A表和B表连接. 通过A表的字段1和b表的字段2进行连接。
on后面的都是主外键关系
select ... from A xxx join B on A.字段1 = b.字段2
-- 查询每门课程被选修的学生数
-- count(*)
-- group by cid
select c.cid,c.cname, count(*) from sc inner join course c on sc.c_id = c.cid group by c.cid, c.cname
-- 查询所有学生的选课情况
select s.sname, c.cname from stu s left join sc on s.sid= sc.s_id left join course c on sc.c_id = c.cid
-- 查询任何一门课程成绩在70分以上的姓名、课程名称和分数
-- score > 70 sc
-- sname student
-- cname course
select s.sname, c.cname, sc.score from stu s inner join sc on s.sid = sc.s_id inner join course c on sc.c_id = c.cid
where sc.score > 70
pip install pymysql
import pymysql
# 链接数据库
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='test123456',
database='spider_back'
)
# 创建游标,游标执行增删改查
cursor = conn.cursor()
try:
cursor = conn.cursor()
result = cursor.execute("insert into stu(sname, address, gender) values ('张三', '恒大别野', 1)")
print(cursor.lastrowid) # 获取自增的ID值
print(result) # result是该sql会影响多少条数据
conn.commit() # 提交
except:
conn.rollback() # 回滚
try:
cursor = conn.cursor()
result = cursor.execute("update stu set gender = 2 where sid = 12")
print(result) # result是该sql会影响多少条数据
conn.commit() # 提交
except:
conn.rollback() # 回滚
try:
cursor = conn.cursor()
result = cursor.execute("delete from stu where sid = 12")
print(result) # result是该sql会影响多少条数据
conn.commit() # 提交
except:
conn.rollback() # 回滚
# 查询
from pymysql.cursors import DictCursor
# cursor = conn.cursor(DictCursor) # 使用字典游标. 查询出的结果自动保存在字典中
cursor = conn.cursor() # 默认游标. 查询出的结果自动保存在元组中
sql = """
select * from stu
"""
ret_num = cursor.execute(sql)
# result = cursor.fetchall() # 获取全部结果
# result = cursor.fetchmany(5) # 获取部分结果
result = cursor.fetchone() # 获取单个结果
print(result)
# 一个游标如果被拿空了. 则不能再次获取内容.
result = cursor.fetchone() # 获取单个结果, 可以连续获取
print(result)
import pymysql
from pymysql.cursors import DictCursor
class NoDataBaseException(Exception):
pass
class DBHelper:
def __init__(self, database=None, host="localhost", port=3306, username="root", password="123456"):
if database:
self.conn = pymysql.connect(
host=host,
port=port,
user=username,
password=password,
database=database
)
else:
raise NoDataBaseException("没有提供正确的数据库")
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
return self.conn.close()
def _change(self, sql, *args, isInsert=False):
cursor = self.conn.cursor()
try:
rownum = cursor.execute(sql, args)
self.conn.commit()
if isInsert:
return cursor.lastrowid
else:
return rownum
except Exception as e:
print("报错了", e)
self.conn.rollback()
finally:
cursor.close()
def insert(self, sql, *args):
return self._change(sql, *args, isInsert=True)
def update(self, sql, *args):
return self._change(sql, *args)
def delete(self, sql, *args):
return self._change(sql, *args)
def query_list(self, sql, *args):
cursor = self.conn.cursor()
try:
cursor.execute(sql, args)
result = cursor.fetchall()
return result
finally:
cursor.close()
def query_one(self, sql, *args):
cursor = self.conn.cursor()
try:
cursor.execute(sql, args)
result = cursor.fetchone()
return result
finally:
cursor.close()
if __name__ == '__main__':
with DBHelper("spider_back") as db:
# result = db.query_list("select * from stu where gender=%s and address like %s", 1, "%北京%")
# print(result)
result = db.delete("delete from stu where sid = %s", 10)
print(result)
1, 打开mysql命令行.
2, 输入以下内容
GRANT ALL PRIVILEGES ON *.* TO '用户名'@'%' IDENTIFIED BY '密码' WITH GRANT OPTION;
FLUSH PRIVILEGES;