> 文章列表 > python数据库-2

python数据库-2

python数据库-2

数据类型

char(n):字符串,最大存储255个字符;n表示字符长度

varcher(n):最大存储65535个字符

enum:在指定的数据中选择一个数据(单选)

set:在指定的数据中选择一个或多个数据(多选)

数值类型

int(n):存储整数,范围在±21以内,创建数据表的时候,不管int后面指定多长,做大只能存放11个数字

float(m,d):单精度浮点型,留存小数点后6-7位小数(m表示数据的总长度,d表示小数位数)

double(m,d):双精度浮点类型,留存小数点后15位小数(m表示数据的总长度,d表示小数位数)

注:浮点数数据保存会存在精度丢失问题

时间类型

year:年

date:年月日(“年-月-日”)

time:时分秒(“时:分:秒”)

datetime:年月日时分秒(“年-月-日 时:分:秒)

注:写入时间类型时,必须使用引号包括

表操作

创建表

/*创建表
create table 表名(字段名  数据类型,字段名  数据类型
);
*/create table test(name char(5),garden enum('男' , '女'),age int(3),height float(3 , 2),	birthday datetime
)charset=utf8;/*注:因为我创建库的时候报错1291,所以在最后加上utf8编码(无报错可不加)*/

表数据插入

可以一次添加多条数据或单条数据,同样也可以指定添加单条或多条

insert into test values
('汪鑫' , '男' , 24  , 1.7 , '1999-9-9 5:20:25');
('轻岚' , '男' , 25  , 1.75 , '1998-9-9 5:20:25');
('曹洪清' , '男' , 26  , 1.77 , '1997-9-9 5:20:25');
('圈圈' , '女' , 18  , 1.77 , '2006-9-9 5:20:25');
('圈圈' , '女' , 18  , 1.77 , '2006-9-9 5:20:25');/*注:报错1055,需要执行sql代码select@@sql_mode;查看一下,然后找到ONLY_FULL_GROUP_BY,在配置文件my.ini中删除掉。重新启动服务就行了虽然报错,但是对操作毫无影响*//*添加name列和age列*/
insert into test(name,age)VALUES
('爆排气孔' , 18),
('小豆腐' , 66),
('小黑子' , 51);

表字段的操作

查看表结构

查看表中的字段类型,长度和约束

desc test;	

字段的增加

默认在表末尾增加

alter table test add scr double(4,1)

添加字段到最前面

alter table test add id int first;

添加到某一个字段之后

alter table test add weight double(4,2) after age;

字段长度/数据类型的修改

修改长度 不能小于原有的长度 ,否则原有的数据就会被破坏,不可修复

alter table test modify column weight double(5,2);
alter table test modify column scr int(5);
desc test;

字段名修改

alter table test change id num int;

删除字段

alter table test drop column scr;

清空表数据

delete from test;

修改表名

alter table test rename test1;

删除表

drop table test;

表数据查询

查询表中的所有字段的所有数据

select * from test;

查询指定字段的所有数据

select id…… from test;

数据查询

select * from test;select name , age ,birthday from test;select name from test;

where 子句

比较符号
=
!=
>
<
>=
<=逻辑运算
and
or
not
(数字要从小到大)
between 在两个值之间
not between
in 在指定集合中
not in

查询表中的所有字段的所有数据

select * from test where  age>15;

查询指定字段的所有数据

select age from test where age<50;
select name from test where age in(15,18,24,25);
select name from test where age not in(15,18,24,25);

聚合函数

聚合函数不可以出现在where子句中having
– 求平均值
avg(字段名)
– 求最大值
max(字段名)
– 求最小值
min(字段名)
– 求和
sum(字段名)
– 统计一个字段的数据条数
count(字段名)

select avg(age) from test;select count(name) from test;select max(height) from test;