SQL语法特征

image-20250705163608687

库管理

  • 查看数据库

show databases;

  • 使用数据库

use 数据库名称;

  • 创建数据库

create database 数据库名称 [charset utf8]; // []可写可不写

  • 删除数据库

drop database 数据库名称;

  • 查看当前使用的数据库

select database();

DDL-表管理

  • 查看有哪些表

show tables; 需要先选择数据库

  • 创建表

create table 表名称(

​ 列名称 列类型,

​ ……

);

类型

int – 整数

float – 浮点型

varchar(长度) – 文本,长度为数字,做最大长度限制

date – 日期类型

timestamp – 时间戳类型

  • 删除表

drop table 表名称;

drop table if exists 表名称;

DML

用来对数据库中表的数据记录进行更新

数据插入

语法:

insert into 表[(列1,列2,……,列n)] values(值1,值2,……,值n),[(值1,值2,……,值n),(值1,值2,……,值n),……]

1
2
3
4
5
6
7
8
9
10
11
12
13
use world;

show tables;

create table animal(

​ age int,

​ nam varchar(10)

);

insert into animal(age) values(1),(2)

其中13行的animal(age)中的元素age等可以省略

数据删除

语法:

delete from 表名称 [where 条件判断];

条件格式:列 操作符 值

操作符:= < > <= >= != 等等

数据更新

updata 表名 set 列=值 [where 条件判断];

数据查询

select 字段列表|* from 表; //*代表全部

如:select id,name from Student;

  • 过滤

select 字段列表|* from 表 where 条件判断;

分组聚合

select 字段|聚合函数 from 表 [where 条件] group by 列

聚合函数

sun(列) 求和

avg(列) 求平均值

min(列) 求最小值

max() 求最大值

count() 求数量

结果排序

select 列|聚合函数|* from 表

where ……

group by ……

order by … [asc(从小到大) | desc(从大到小)]

  • 结果分页

用limit关键字,对查询结果进行数量限制或分页显示

select 列|聚合函数|* from 表

where ……

group by ……

order by … [asc(从小到大) | desc(从大到小)]

limit n,[ m ] //如果只有n,意思是输出前n条,

​ //如果有n,m,意思是跳过前n条,再往后输出m条

Python操作MySQL操作

1
2
3
4
5
6
7
8
9
10
11
12
from pymysql import Connection


# 构建到MySQL数据库的链接
conn = Connection(
host='localhost',
port=3306,
user='root',
password='shenentao520',
)
print(conn.get_server_info())

执行非查询性质的sql语句

1
2
3
4
5
6
# 获取游标对象
cursor = conn.cursor()
# 先选择数据库
conn.select_db('test')
# 使用游标对象,执行sql语句
cursor.execute('create table test (id int, name varchar(20))')

执行查询性质的sql语句

1
2
3
4
# 使用游标对象,执行sql语句
cursor.execute('select * from country')
result: tuple = cursor.fetchall()
print(result)
1
2
# 关闭连接
conn.close()

执行插入性质的sql语句

执行插入语句的时候,并不会直接完成,而是要我们进行一个确认

通过连接对象.commit()进行确认即可

1
2
3
cursor.execute("insert into animal(nam) values('猫')")

conn.commit()
  • 自动commit

autocommit=True

1
2
3
4
5
6
7
conn = Connection(
host='localhost',
port=3306,
user='root',
password='shenentao520',
autocommit=True
)