目录
1.数据库的操作
1.1 显示当前的数据库
show databases;
1.2 创建数据库
create database [if not exists] db_name [create_specification]...
create_specification:
[default] character set charset_name
[default] collate collation_name
说明:
- []是可选项
- character set:指定数据库采用的字符集
- collate:指定数据库字符集的校验规则
示例:
- 创建名为test_1的数据库
create database test_1;
- 如果系统没有test_2的数据库,则创建一个名为test_2的数据库,如果有则不创建
create database if not exists test_2; - 如果系统没有test的数据库,则创建一个使用utf8mb4字符集的test数据库,如果有则不创建
create database if not exists test character set utf8mb4;
1.3 使用数据库
use 数据库名;
1.4 删除数据库
drop database [if exists] db_name;
说明:数据库删除以后,内部看不到对应的数据库,里面的表和数据全部被删除
2.常见的数据类型
2.1 数值类型
分为整形和浮点型
| 数据类型 | 大小 | 说明 | 对应Java类型 |
| bit[(m)] | m指定位数,默认为1 | 二进制数,m范围从1到64,存储数据范围从0到2^m-1 | 常见Boolean对应bit,此时默认是1位,即只能存0和1 |
| tinyint | 1字节 | Byte | |
| smallint | 2字节 | Short | |
| int | 4字节 | Integer | |
| bigint | 8字节 | Long | |
| float(m,d) | 4字节 | 单精度,m指定长度,d指定小数位数。会发生精度丢失 | Float |
| double(m,d) | 8字节 | Double | |
| decimal(m,d) | m/d最大值+2 | 双精度,m指定长度,d表示小数点位数。精确数值 | BigDecimal |
| numeric(m.d) | m/d最大值+2 | 和decimal一样 | BigDecimal |
扩展资料
数值类型可以指定为无符号(unsigned),表示不取负数。
1字节(bytes)= 8bit。
对于整型类型的范围:
- 有符号范围:-2^(类型字节数*8-1)到2^(类型字节数*8-1)-1,如int是4字节,就是-2^31到2^31-1
- 无符号范围:0到2^(类型字节数*8)-1,如int就是2^32-1
尽量不使用unsigned,对于int类型可能存放不下的数据,int unsigned同样可能存放不下,与其如此,还不如设计时,将int类型提升为bigint类型
2.2 字符串类型
| 数据类型 | 大小 | 说明 | 对应Java类型 |
| varchar(size) | 0-65 535字节 | 可变长度字符串 | String |
| text | 0-65 535字节 | 长文本数据 | String |
| mediumtext | 0-16 777 215字节 | 中等长度文本数据 | String |
| blob | 0-65 535字节 | 二进制形式的长文本数据 | byte[] |
2.3 日期类型
| 数据类型 | 大小 | 说明 | 对应Java类型 |
| datetime | 8字节 | 范围从1000到9999年,不会进行时区的检索及转换。 | java.util.Date、 java.sql.Timestamp |
| timestamp | 4字节 | 范围从1970到2038年,自动检索当前时区并进行转换。 | java.util.Date、 java.sql.Timestamp |
3.表的操作
需要操作数据库中的表时,需要先使用该数据库:
use 数据库名;
3.1 查看表结构
desc 表名;
示例:

3.2 创建表
create table table_name(
field1 datatype,
field2 datatype,
field3 datatype
);
可以使用comment增加字段说明。
示例:
create table test (
id int,
name varchar(20) comment '姓名',
password varchar(50) comment '密码',
age int,
sex varchar(1),
birthday timestamp,
amout decimal(13,2),
resume text
);
3.4 删除表
drop [temporary] table [if exists] table_name [, table_name] ...
示例:
-- 删除test表
drop table test;
-- 如果存在test表,则删除test表
drop table if exists test;
5万+

被折叠的 条评论
为什么被折叠?



