Python MySQL 数据库技术 part 3

本文详细介绍了Python操作MySQL数据库的DML(数据操作)和DQL(数据查询)语法,包括如何添加、修改和删除数据,以及基础查询、条件查询、分组、排序和分页等操作。同时,还涵盖了数据库导入导出和权限管理,包括创建、授权和回收用户权限。最后,讲解了如何使用Python的pymysql模块与MySQL交互。
摘要由CSDN通过智能技术生成

8.MySQL数据操作 DML

增删改

8.1 添加数据

insert into 表名[(字段列表)] values(值列表);
1) 标准添加(指定所有字段,给定所有值)
insert into 表名(字段1,字段2,字段3) values(值1,值2,值3);
–insert into user(name,age,sex) values(‘zhangsan’,20,‘male’);
2) 指定部分字段添加值
insert into 表名(字段1,字段3) values(值1,值3);
3) 不指定字段添加值
insert into 表名 values(值1,值2,值3);
此时的值不能缺少任何一个!
4) 批量添加值
insert into 表名 values(a值1,a值2,a值3),(b值1,b值2,b值3);

8.2 修改数据

update 表名 set 字段1=值1,字段2=值2 where 条件;
-字段可为一个字段或多个字段
–update users set age=33 where id=3;
–update users set age=17,sex=‘male’ where id in(5,9); 注意!
update 表名 set 字段=字段+值 where 条件;

8.3 删除数据

delete from 表名 [where 字段=值];
–delete from users where id>=10 and id<=15;
–delete from users where id between 10 and 15;

9.MySQL数据查询 DQL

select 字段列表|* from 表名
[where 搜索条件]
[group by 分组字段 [having 分组条件]]
[order by 排序字段 排序规则]
[limit 分页参数];

9.1 基础查询

1) 查询表中所有列 所有数据
select * from 表名;
2) 指定字段列表进行查询
select 字段1,字段2 from 表名;

9.2 where 条件查询

  • where子句中指定任何条件
  • 使用 and 或者 or 指定一个或多个条件
  • where条件可运用在 update 和 delete 语句后面
  • where子句中 if 条件,根据mysql表中的字段值来进行数据的过滤
    示例:
    select * from 表名 where 字段=某个值;
    select * from users where age>20;
    select * from users where age not between 20 and 25;
    select * from users where age >=20 and age <=26 and sex =‘male’;
and 和 or 使用时注意

and 和 or 在同一条件句时,会优先处理 and
select * from users where age=20 or age=25 and sex=‘male’;
– 使用小括号来关联相同的条件
select * from users where (age=20 or age=25) and sex=‘male’;

like 子句

可以在where条件中使用=<>等符号进行条件的过滤,若想查询某个字段是否包含,
使用 like 语句 进行某个字段的模糊搜索
% 代表任意个任意字符;
_ 代表任意一个字符。
select * from users where name like ‘%n’;
select * from users where name like ‘__’; --任意两个字符
注意:
where子句中的like 在使用%_时,效率不高。
尽量不去使用,若使用,尽量不要把通配符放在开头!

9.3 MySQL中的统计函数(聚合函数)

max(),min(),count(),sum(),avg()
–求表中最大 最小 总和 平均年龄
select max(age),min(age),sum(age),avg(age) from users;
–上面数据中的列都是在查询时使用的函数名,不方便阅读和后期的调用,可以通过别名方式美化
select max(age) as max_age,min(age) as min_age,
sum(age) as sum_age,avg(age) as avg_age from users;
–统计表中的数据量

select count(*) from users;
+----------+
| count(*) |
+----------+
|        7 |
+----------+
1 row in set (0.10 sec)
select count(id) from users;
| count(id) |
+-----------+
|         7 |
+-----------+
1 row in set (0.00 sec)

count(*): 按照表中所有的列进行数据统计,只要其中一列上有数据,就可以计算。
count(id):按照指定的id字段进行统计,也可是用别的字段统计,但是
若指定的列上出现了NULL值,那么为NULL的数据不会被统计。
如,若address列有一个NULL,则 count(address) 结果为

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值