数据库表与字段和引擎操作

数据库表与字段和引擎操作

一、数据库表操作

  1. 查看当前数据库中的表

格式:show tables;

  1. 简单创建表

格式: create table 表名 (属性名1 类型(长度) 约束,...属性名n 类型(长度) 约束) engine=引擎 default charset=utf8;

eg>>: create table test (id int primary key auto_increment, name varchar(20));

注:1) 表字符编码跟数据库编码走

​ 2) 长度和约束在某些情况下是可以省略的

  1. 查看表创建完整语句

格式:show create table 表名;

eg>>: show create table test;

  1. 查看表结构

格式:desc 表名;

eg>>: desc test;

二、表修改

  1. 修改字符编码

格式:alter table 表名 charset="字符编码";

eg>>:alter table test charset='utf';

  1. 修改表名

格式:alter table 旧表名 rename 新表名;

eg>>: alter table test rename new_test;

  1. 删除表名

格式:drop table 表名

eg>>: drop table new_test;

三、字段修改

  1. 修改字段类型

格式:alter table 表名 modify 字段名 字段类型[长度] 约束条件;

eg>>: alter table test modify name varchar(16) unique;

  1. 修改字段名

格式:alter table 表名 change 旧字段名 新字段名 字段类型[长度] 约束条件;

eg>>: alter table test change name new_name varchar(18) unique;

  1. 添加字段

格式:alter table 表名 add 新字段名 字段类型[长度] 约束条件 first | [after 字段名] ;

eg>>: alter table test add sex enum('男', '女') default '男'; # 默认在字段末尾

eg>>: alter table test add height float(7, 2) default 0 first; # 首位

eg>>: alter table test add weight float(7, 2) default 0 after height; # 某字段之后

  1. 删除字段

格式:alter table 表名 drop 字段名;

eg>>: alter table test drop height;

四、数据库表的引擎

  1. 引擎作用

    驱动数据的方式 -进行 数据库优化

    引擎是建表时规定, 提供给表使用的, 不是数据库

  2. 查看数据库库所有引擎

格式:show engines;

  1. 创建引擎

格式:create table 表名(字段...)engine=引擎名称;

eg>>: create table test (id int, name char(10)) engine=innodb;

  1. 引擎分类
    • innodb(默认): 支持事务, 行级锁, 外键
    • myisam: 查询效率要优于innodb, 当不需要支持事务, 行级锁, 外键, 可以通过设置myisam来优化数据库
    • blackhole:黑洞,存进去的数据都会消失(可以理解不存数据)
    • memory:表结构是存储在硬盘上的,但是表数据全部存储在内存中
在当下的阶段,必将由程序员来主导,甚至比以往更甚。
原文地址:https://www.cnblogs.com/randysun/p/11629796.html