mysql数据库与表的操作_数据库-mysql数据库和表操作

一:数据库查询增加删除

1)mysql数据库查询:show databases

MariaDB [mysql]>show databases;+--------------------+

| Database |

+--------------------+

| information_schema |

| mysql |

| performance_schema |

| test |

+--------------------+

4 rows in set (0.00 sec)

2)数据库创建:create database test2 charset utf8;

注:charset utf8可以支持中文

MariaDB [mysql]>create database test2 charset utf8;

Query OK,1 row affected (0.00 sec)

3) 数据库删除:drop database test2

MariaDB [mysql]>drop database test2 ;

Query OK, 0 rows affected (0.00 sec)

二:数据表的增删改

1)表的创建:CREATE TABLE table_name (column_name column_type);

MariaDB [test2]>create table student(-> stu_id int notnull auto_increment,-> name char(32) notnull,-> age int notnull,->register_date date,->primary key (stu_id)-> )engine=InnoDB default charset=utf8;

Query OK, 0 rows affected (0.01 sec)

注:

如果你不想字段为 NULL 可以设置字段的属性为 NOT NULL, 在操作数据库时如果输入该字段的数据为NULL ,就会报错。

AUTO_INCREMENT定义列为自增的属性,一般用于主键,数值会自动加1。

PRIMARY KEY关键字用于定义列为主键。 您可以使用多列来定义主键,列间以逗号分隔。

ENGINE 设置存储引擎,CHARSET 设置编码。

2)表的删除:DROP TABLE table_name ;

MariaDB [test2]>drop table student;

Query OK, 0 rows affected (0.01 sec)

3)需要修改数据表名或者修改数据表字段时,就需要使用到MySQL ALTER命令

A)增加字段:alter table student add sex char(2) not null;

MariaDB [test2]> alter table student add sex char(2) notnull;

Query OK, 0 rows affected (0.01sec)

Records: 0 Duplicates: 0 Warnings:

B)删除字段:alter table student drop register_date;

MariaDB [test2]>alter table student drop register_date;

Query OK, 0 rows affected (0.01sec)

Records: 0 Duplicates: 0 Warnings: 0

C)如果需要修改字段类型及名称, 你可以在ALTER命令中使用 MODIFY 或 CHANGE 子句

、alter table student modify name char(10) not null; (语法要写全)

MariaDB [test2]> alter table student modify name char(10) notnull;

Query OK, 0 rows affected (0.01sec)

Records: 0 Duplicates: 0 Warnings: 0

使用 CHANGE 子句, 语法有很大的不同。 在 CHANGE 关键字之后,紧跟着的是你要修改的字段名,然后指定新字段名及类型

alter table student change name name2 char(10) not null;

MariaDB [test2]> alter table student change name name2 char(10) notnull;

Query OK, 0 rows affected (0.01sec)

Records: 0 Duplicates: 0 Warnings: 0

D)ALTER TABLE 对 Null 值和默认值的影响

当你修改字段时,你可以指定是否包含只或者是否设置默认值。

MariaDB [test2]> alter table student modify sex char(2) not null default'F';

Query OK, 0 rows affected (0.00sec)

Records: 0 Duplicates: 0 Warnings: 0

E) 修改表名:alter table student rename to student2;

MariaDB [test2]>alter table student rename to student2;

Query OK, 0 rows affected (0.01 sec)


版权声明:本文为weixin_35662171原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。