数据类型

  • 整数:int,bit
  • 小数:decimal
  • 字符串:varchar,char
  • 日期时间: date, time, datetime
  • 枚举类型(enum)

特别说明的类型如下:

  • decimal表示浮点数,如decimal(5,2)表示共存5位数,小数占2位
  • char表示固定长度的字符串,如char(3),如果填充’ab’时会补一个空格为’ab ‘
  • varchar表示可变长度的字符串,如varchar(3),填充’ab’时就会存储’ab’
  • 字符串text表示存储大文本,当字符大于4000时推荐使用
  • 对于图片、音频、视频等文件,不存储在数据库中,而是上传到某个服务器上,然后在表中存储这个文件的保存路径

    约束

  • 主键primary key:物理上存储的顺序
  • 非空not null:此字段不允许填写空值
  • 惟一unique:此字段的值不允许重复
  • 默认default:当不填写此值时会使用默认值,如果填写时以填写为准
  • 外键foreign key:对关系字段进行约束,当为关系字段填写值时,会到关联的表中查询此值是否存在,如果存在则填写成功,如果不存在则填写失败并抛出异常
  • 说明:虽然外键约束可以保证数据的有效性,但是在进行数据的crud(增加、修改、删除、查询)时,都会降低数据库的性能,所以不推荐使用,那么数据的有效性怎么保证呢?答:可以在逻辑层进行控制

数值类型(常用)

类型 字节大小 有符号范围(Signed) 无符号范围(Unsigned)
TINYINT 1 -128 ~ 127 0 ~ 255
SMALLINT 2 -32768 ~ 32767 0 ~ 65535
MEDIUMINT 3 -8388608 ~ 8388607 0 ~ 16777215
INT/INTEGER 4 -2147483648 ~2147483647 0 ~ 4294967295
BIGINT 8 -9223372036854775808 ~ 9223372036854775807 0 ~ 18446744073709551615

字符串

类型 字节大小 示例
CHAR 0-255 类型:char(3) 输入 ‘ab’, 实际存储为’ab ‘, 输入’abcd’ 实际存储为 ‘abc’
VARCHAR 0-255 类型:varchar(3) 输 ‘ab’,实际存储为’ab’, 输入’abcd’,实际存储为’abc’
TEXT 0-65535 大文本

日期时间类型

类型 字节大小 示例
DATE 4 ‘2020-01-01’
TIME 3 ‘12:29:59’
DATETIME 8 ‘2020-01-01 12:29:59’
YEAR 1 ‘2017’
TIMESTAMP 4 ‘1970-01-01 00:00:01’ UTC ~ ‘2038-01-01 00:00:01’ UTC

数据库

  • 创建数据库

create database 数据库名 charset=utf8;

  • 删除数据库
    1. drop database python;

数据表

  • 创建表

    1. create table students(
    2. id int unsigned primary key auto_increment not null,
    3. name varchar(20) default '',
    4. age tinyint unsigned default 0,
    5. height decimal(5,2),
    6. gender enum('男','女','人妖','保密'),
    7. cls_id int unsigned default 0
    8. )
  • 修改表-添加字段

    1. alter table students add birthday datetime;
  • 修改表-修改字段:重命名版

    1. alter table 表名 change 原名 新名 类型及约束;
    2. 例:
    3. alter table students change birthday birth datetime not null;
  • 修改表-修改字段:不重命名版

    1. alter table 表名 modify 列名 类型及约束;
    2. 例:
    3. alter table students modify birth date not null;
  • 修改表-删除字段

    1. alter table 表名 drop 列名;
    2. 例:
    3. alter table students drop birthday;
  • 删除表

    1. drop table 表名;
    2. 例:
    3. drop table students;

    增删改查(curd)

    查询基本使用

    1. select 列1,列2,... from 表名;
    2. 例:
    3. select id,name from classes;

    增加

  • 全列插入:值的顺序与表中字段的顺序对应

    1. insert into 表名 values(...)
    2. 例:
    3. insert into students values(0,’郭靖‘,1,'蒙古','2016-1-2');
  • 部分列插入:值的顺序与给出的列顺序对应

    1. insert into 表名(列1,...) values(值1,...)
    2. 例:
    3. insert into students(name,hometown,birthday) values('黄蓉','桃花岛','2016-3-2');
  • 全列多行插入:值的顺序与给出的列顺序对应

    1. insert into 表名 values(...),(...)...;
    2. 例:
    3. insert into classes values(0,'python1'),(0,'python2');
    1. insert into 表名(列1,...) values(值1,...),(值1,...)...;
    2. 例:
    3. insert into students(name) values('杨康'),('杨过'),('小龙女');

    修改

    1. update 表名 set 列1=值1,列2=值2... where 条件
    2. 例:
    3. update students set gender=0,hometown='北京' where id=5;

    删除

    1. delete from 表名 where 条件
    2. 例:
    3. delete from students where id=5;

    条件

    where后面支持多种运算符,进行条件的处理

  • 比较运算符

  • 逻辑运算符
  • 模糊查询
  • 范围查询
  • 空判断

    比较运算符

  • 等于: =

  • 大于: >
  • 大于等于: >=
  • 小于: <
  • 小于等于: <=
  • 不等于: != 或 <>

    逻辑运算符

  • and

  • or
  • not

    模糊查询

  • like

  • %表示任意多个任意字符
  • _表示一个任意字符

    1. 查询姓黄的学生
    2. select * from students where name like '黄%';
    3. 查询姓黄并且“名”是一个字的学生
    4. select * from students where name like '黄_';
    5. 查询姓黄或叫靖的学生
    6. select * from students where name like '黄%' or name like '%靖';

    范围查询

  • in表示在一个非连续的范围内

    1. 查询编号是1或3或8的学生
    2. select * from students where id in(1,3,8);
    3. 查询编号为3至8的学生
    4. select * from students where id between 3 and 8;
    5. 查询编号是3至8的男生
    6. select * from students where (id between 3 and 8) and gender=1;

    空判断

  • 判空is null

  • 判非空is not null

    1. select * from students where height is not null and gender=1;

    优先级

  • 优先级由高到低的顺序为:小括号,not,比较运算符,逻辑运算符

  • and比or先运算,如果同时出现并希望先算or,需要结合()使用

    排序

    select * from 表名 order by 列1 asc|desc [,列2 asc|desc,…]

    说明
  • 将行数据按照列1进行排序,如果某些行列1的值相同时,则按照列2排序,以此类推

  • 默认按照列值从小到大排列(asc)
  • asc从小到大排列,即升序
  • desc从大到小排序,即降序

    1. 例1:查询未删除男生信息,按学号降序
    2. select * from students where gender=1 and is_delete=0 order by id desc;
    3. 例2:查询未删除学生信息,按名称升序
    4. select * from students where is_delete=0 order by name;
    5. 例3:显示所有的学生信息,先按照年龄从大-->小排序,当年龄相同时 按照身高从高-->矮排序
    6. select * from students order by age desc,height desc;

    聚合函数

    总数

  • count(*)表示计算总行数,括号中写星与列名,结果是相同的 ```python 例1:查询学生总数

select count(*) from students;

  1. <a name="lr6VM"></a>
  2. #### 最大值
  3. - max(列)表示求此列的最大值
  4. <a name="WydFZ"></a>
  5. #### 最小值
  6. - min(列)表示求此列的最小值
  7. <a name="X5S4q"></a>
  8. #### 求和
  9. - sum(列)表示求此列的和
  10. ```python
  11. 平均年龄
  12. select sum(age)/count(*) from students where gender=1;

平均值

  • avg(列)表示求此列的平均值

    数据库Python操作

    执行插入操作

    1. import time
    2. db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
    3. cur=db.cursor()
    4. db.begin()
    5. sql="INSERT INTO student(NAME,score,tim) VALUES ('%s',%d,'%s')"
    6. data=('HW',90,tt)
    7. try:
    8. cur.execute(sql%data)
    9. except Exception as e:
    10. print(e)
    11. db.rollback()
    12. else:
    13. db.commit()
    14. finally:
    15. cur.close()
    16. db.close()

    同时插入多条数据

    ```python import pymysql import time start=time.time() tt=time.strftime(‘%Y-%m-%d %H:%M:%S’,time.localtime(time.time())) db=pymysql.connect(host=’localhost’,user=’root’,password=’123456’,port=3306,db=’people’) cur=db.cursor() db.begin() sql=”insert into student(NAME,score,tim)values(%s,%s,%s)” def get(): ab=[] for y in range(1,100000): if y>=100:
    data=('user-'+str(y),str(str(float('%.f'%(y%100)))),tt)
    
    else:
    data=('user-'+str(y),str(y),tt)
    
    ab.append(data) return ab

try: data=get() cur.executemany(sql,data)#data为列表,列表元素为() except Exception as e: print(e) db.rollback() else: db.commit() finally: print(‘插入数据完毕’) cur.close() db.close() end=time.time() print(‘用时:’,str(end-start))

<a name="O2KSP"></a>
#### 执行查询操作
```python
import pymysql
import time
tt=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
db=pymysql.connect(host='localhost',user='root',password='123456',port=3306,db='people')
cur=db.cursor()
db.begin()
sql="select * from student;"
try:
  cur.execute(sql)
  res=cur.fetchall() 查询数据库中的数据
  for y in res:
    print(y) 打印数据库中标的所有数据,以元祖的形式
except Exception as e:
  print(e)
  db.rollback()
else:
  db.commit()
finally:
  cur.close()
  db.close()