当前位置: 移动技术网 > IT编程>数据库>Mysql > MySql基本操作(一)

MySql基本操作(一)

2018年09月16日  | 移动技术网IT编程  | 我要评论

1-创建数据库

create database 数据库名称;

例如:

create database myschool;

2-查看数据库列表

show databases;  #执行查看已存在数据库

3-选择数据库

use 数据库名;

例如:

use myschool;

4-删除数据库

drop database 数据库名;

例如:

drop databse myschool;

5-创建表

create [if not exists]table 表名

(

  字段1 数据类型 primary key,  #主键

  ........

 

);

例如:

#创建表格
create table `student`
(
`studentno` int (4) not null comment '学号' primary key, #非空,主键
`loginpwd` varchar(20) not null comment '密码', #非空,
`studentname` varchar(50) not null comment '学生姓名', #非空
`sex` char (2) default'男' not null comment '性别', #非空,默认值为’男‘
`gradeid` int(4) unsigned comment '年级编号', #无符号数
`phone` varchar(50) comment '联系方式',
`address` varchar(255) default'地址不详' comment'地址',
`borndate` datetime comment '出生日期', #时间
`email` varchar(50) comment '邮箱账号',
`identitycard` varchar(18) unique key comment '身份证号' #唯一


)charset='utf8' comment="学生表"; #表注释“学生表”

6-查看表

show tables;#查看当前数据库中存在的表

例如:

 

desc 表名;#查看当前表格的定义

例如:

 7-删除表

drop table [if not exists] 表名;

例如:

drop table student;

8-修改表名

alter table<旧表名>rename[to]<新表名>;

例如:

alter table demo1 rename demo2;

9-添加字段

alter table 表名 add 字段名 数据类型 [属性];

例如:

alter table demo2 add `password` varchar(32) not null;

10-修改字段

alter table 表名 change 原字段名 新字段名 数据类型 [属性];

例如:

 alter table demo2 name username char(10) not null;

11-删除字段

alter table 表名 drop 字段名;

例如:

alter table demo2 drop `password`;

12-添加主键约束

alter table 表名 add constraint 主键名 primary key 表名(主键字段);

例如:

alter table `grade` add constraint `pk_grade` primary key `grade`(`gradeid`);

13-添加外键约束

alter table 表名 add constraint 外键名 foreign key references 关联表名(关联字段);

例如:设置student表的gradeid字段与grade表的gradeid字段建立主外键关联。

alter table student add constraint fk_student_grade foreign key (gradeid)

references grade(gradeid);

 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网