- 1.修改表名:alter table 原表名 rename to 新表名;
alter table college rename to coll;
- 2.修改字段名:alter table student change 原字段名 新字段名 data_type(字段类型);
alter table student change id num varchar(8);
- 3.修改字段类型:alter table student modify id varchar(4);#强烈建议不要这样用
- 4.添加字段:alter table student add hobby varchar(64);
- 5.删除字段:alter table student drop hobby;
约束条件
- 约束条件一般用在创建表的时候
- 1.默认约束:default,插入数据时,没有赋值,自动赋予默认值,没默认值,默认为null, alter table student add hobby enum("xiaoge","dalong") default "xiaoge";
- 2.非空约束:not null,限制一个字段的值不能为空,insert时必须为该字段赋值,特别的是enum(a,b)被修饰时默认是a,非空字符不能与null合用,一般与default配合使用
alter table student add addr varchar(128) not null default "zhaodong";
- 3.唯一约束:限制一个字段的值不能重复,确保字段中的值唯一
alter table student modify id int unique key;
- 4.主键:primary key,通常每张表都需要一个主键来体现唯一性,每张表里只有一个主键,主键=非空+唯一
alter table student modify id int primary key;
- 5.自增长:auto_increment要求用在主键上,自动编号,和主键组合使用,一个表只能有一个自增长,被删掉的不会自动添加
alter table score modify id int primary key auto_increment;
- 6.外键:foreign key,保证多表数据的一致性,外键能关联另一张表的主键,外键表有的,主键表一定有;主键表没有的,外键表一定没有
事物
- 为了保证操作的一致性,(例如:转账,减少A的钱增加B的钱等),要么都成功,要么都不成功
- mysql默认开启事务物,事物只支持数据库引擎
mysql事物的两种方式:
1.直接用set来改变mysql的自动提交模式
- set autocommit = 0 #禁止自动提交
- set autocommit = 1 #开启自动提交
2.用begin,rollback,commit来实现
- 步骤:
1.begin开始一个事物,检测是否都成功
if 都成功了:
commit #提交
else:
rollback #回滚