学习内容来源:Bilibili 黑马程序员
一、数据库介绍
组成:

三个层级:库 -> 表 -> 数据
\
二、SQL基础
SQL全称:Structured Query Language,结构化查询语言,用于访问和处理数据库的标准的计算机语言。

语法特征:

1、DDL-库管理





2、DDL-表管理




3、DML
DML:Data Manipulation Language,指数据操作语言,用来对数据中的表的数据记录进行更行
在SQL语句中,字符串的值必须要用单引号包围起来
(1)数据插入INSERT


(2)数据删除DELETE



全部删除:

(3)数据更新

4、DQL
(1)基础数据查询
基础语法:SELECT 字段列表|* FROM 表


查询也可以带有指定条件

(2)分组聚合查询




group by 中出现了哪个列,哪个列才能出现在select中的非聚合中
(3)排序和分页

asc:升序,desc:降序,不写默认升序


从第n+1行开始向后取m行


三、Python操作MySQL


from pymysql import Connection
# 构建到MySQL数据库的链接
conn = Connection(
host='localhost', # 主机名(IP)
port=3306, # 端口
user='root', # 账户
password='hemsworth'# 密码
)
print(conn.get_server_info()) # 8.0.44
# 获取游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db('test')
# 执行sql
cursor.execute('create table student(id int,name varchar(10),age int,gender varchar(2));');
cursor.execute("insert into student values(4, 'l', 18 , '男'), (1, 'y', 17 , '男'), (2, 'f', 16 , '男'), (5, 'm', 11 , '女'), (4, 'f', 14 , '女');")
cursor.execute('select * from student;')
# 获取查询结果
results: tuple = cursor.fetchall()
for r in results:
print(r)
# 关闭链接
conn.close()
# 结果
8.0.44
(4, 'l', 18, '男')
(1, 'y', 17, '男')
(2, 'f', 16, '男')
(5, 'm', 11, '女')
(4, 'f', 14, '女')
插入数据(需要通过commit确认此行为)
确认的两种方式:1、链接对象.commit();2、自动确认:autocommit=True
from pymysql import Connection
# 构建到MySQL数据库的链接
conn = Connection(
host='localhost', # 主机名(IP)
port=3306, # 端口
user='root', # 账户
password='hemsworth'# 密码
)
print(conn.get_server_info()) # 8.0.44
# 获取游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db('test')
# 执行sql
cursor.execute("insert into student values(12, 'lyf', 15 , '男');")
# 确认
conn.commit()
# 关闭链接
conn.close()

from pymysql import Connection
# 构建到MySQL数据库的链接
conn = Connection(
host='localhost', # 主机名(IP)
port=3306, # 端口
user='root', # 账户
password='hemsworth',# 密码
autocommit=True
)
print(conn.get_server_info()) # 8.0.44
# 获取游标对象
cursor = conn.cursor()
# 选择数据库
conn.select_db('test')
# 执行sql
cursor.execute("insert into student values(4, 'l', 18 , '男'), (1, 'y', 17 , '男'), (2, 'f', 16 , '男'), (5, 'm', 11 , '女'), (4, 'f', 14 , '女');")
# 关闭链接
conn.close()

2279

被折叠的 条评论
为什么被折叠?



