DQL_基础查询
基础数据查询
在SQL中,通过select关键字开头的SQL语句,进行数据查询
代码:
select id, name from student; -- 从student这个表里面查询id和姓名
运行的结果:
基础查询_过滤:
就是在表的后面加个 where 条件判断
代码:
select id, name from student where age >= 20; -- 查询年龄大于等于20的人的id和姓名
DQL_分组聚合
基础语法:
DQL_排序分页
排序:
代码:
select * from student where age >= 19 order by age asc; -- 查找到年龄大于20 按照年纪从小到大进行排序
-- 要是从大到小的话 是 desc 默认的是asc
运行结果:
结果分页限制:
代码:
select * from student limit 3; -- 限制个数为3 也就是显示的个数是3个
-- 要是写 3, 2 表示的是跳过前3条 从第4条开始 显示两个
运行的结果:
python操作MySQL
- 首先要获取到mysql数据库的链接 在里面写上 host = 主机名, port = 端口号, user = 用户名, passworld = 密码
基础使用:
from pymysql import Connection
# 获取到MYSQL数据库的链接对象
coon = Connection(
host='localhost', # 主机名 (IP)
port=3306, # 端口
user='root', # 用户名
password='123456' # 密码
)
# 打印MYSQL数据库软件信息
print(coon.get_server_info()) # 8.0.34 版本
# 关闭到数据库的链接
coon.close()
执行SQL语句:
执行非查询性质的SQL语句:
- 还是先链接起来
- 获取游标对象 conn.cursor()
- 选择数据库 conn.select_db()
- 使用游标对象 执行sql语句
- 关闭数据库的链接
代码:
from pymysql import Connection
# 获取到MYSQL数据库的链接对象
conn = Connection(
host='localhost', # 主机名 (IP)
port=3306, # 端口
user='root', # 用户名
password='123456' # 密码
)
# 获取游标对象
cursor = conn.cursor()
conn.select_db("test") # 先选择数据库
# 使用游标对象 执行sql语句
cursor.execute("create table test_pymysql(id int, info varchar(255))")
# 关闭到数据库的链接
conn.close()
运行的结果:
执行查询性质的SQL语句:
- 查询sql语句 fetchall() 方法会返回一个包含所有查询结果的列表,每个结果都是一个元组。
代码:
from pymysql import Connection
# 获取到MYSQL数据库的链接对象
conn = Connection(
host='localhost', # 主机名 (IP)
port=3306, # 端口
user='root', # 用户名
password='123456' # 密码
)
# 获取游标对象
cursor = conn.cursor()
conn.select_db("test") # 先选择数据库
# 使用游标对象 执行sql语句
cursor.execute("select * from student")
# 获取查询结果
results: tuple = cursor.fetchall()
for r in results:
print(r)
# 关闭到数据库的链接
conn.close()
运行的结果:
数据插入:
- 比上面多了一步 也就是 通过commit确认 commit() 是用于将数据库中的更改永久保存的方法。在进行数据的插入、更新或删除等操作后,需要调用 commit() 方法来确保更改被永久保存到数据库中。
代码:
from pymysql import Connection
# 获取到MYSQL数据库的链接对象
conn = Connection(
host='localhost', # 主机名 (IP)
port=3306, # 端口
user='root', # 用户名
password='123456' # 密码
)
# 获取游标对象
cursor = conn.cursor()
conn.select_db("test") # 先选择数据库
# 执行sql
cursor.execute("insert into test_pymysql values(1, '大家好,我叫FindYou.'), (2, 'Code change the world')")
# 通过commit确认 这一步是很重要的
conn.commit()
# 关闭到数据库的链接
conn.close()
运行的结果:
自动commit
autocommit = True # 设置自动提交