网站建设知识
MySQL学习-第一练
2025-07-22 10:00  点击:0

首先按照网上各种教程将MySQL下载下来安装好后,开始了MySQL数据库学习的第一步。

首先是先要启动登录数据库。

1、查看mysql版本

mysql -V

2、Mysql启动、停止、重启常用命令

a、启动方式

1、启动:

service mysql start

safe_mysqld&

b、停止

1

service mysqld stop

c、重启

service mysqld restart

3 登录数据库

本地登陆:mysql -h localhost -uroot -p

MySQL语句入门

DDL-数据定义语言

create drop alter (建库,建表,设置约束)

首先,先创建一个名为animal的数据库。

create database animal character set utf8;

进入创建的数据库

use animal;

为里面添加表

create table species(

id int(8) zerofill,

name varchar(15) not null default ' ',

byname varchar(15) not null default ' ',

foot tinyint(1) not null default 2,

weight float(7,2) not null default 00.00

)charset=utf8;

为表中插入数据

insert into species

(id,name,byname,foot,weight)

values

(1,'tiger','xiaohei',4,252.25);

(4,'mouse','xiaohei',4,2.25);

(6,'dog','xiaohei',4,26.36);

(8,'cat','xiaohei',4,12.23);

为species添加一列名为age,类型为tinyint的列

alter table species add column age tinyint(3) unsigned;

移除新增的这一列

alter table species drop column age;

drop table species;

删除表格

drop database animal;

删除数据库

DML-数据操控语言

增删改 selecet\delect\update\insert

show databases;

使用animal库,并查看当前数据库所有表名

use animal;

show tables;

查看表中记录

select * from species;

select * from species where foot=4;

select name,foot from species;

插入一行记录并删除

insert into species values (5,'fish','yu',0,1.23)

delete from species where name= 'fish';

update species set name='mumu' where id=4;

MySQL的数据类型

1、整型

MySQL数据类型 字节 范围(有符号)

tinyint 1 -128 - 127

smallint 2 -32768 - 32767

mediumint 3 -8388608 - 8388607

int 4 -2147483648 - 2147483647

bigint 8

2、浮点型

float(m,d)单精度浮点型 8位精度(4字节) m总个数,d小数位

double(m,d) 双精度浮点型 16位精度(8字节) m总个数,d小数位

3、定点数

decimal(m,d) 参数m<65,d<30且 d

4、字符串

char(n) 固定长度,最多255个字符

varchar(n) 固定长度,最多65535个字符

text 可变长度,最多65535个字符

char和varchar:

1.char(n) 若存入字符数小于n,则以空格补于其后,查询之时再将空格去掉。所以char类型存储的字符串末尾不能有空格,varchar不限于此。

2.char(n) 固定长度,char(4)不管是存入几个字符,都将占用4个字节,varchar是存入的实际字符数+1个字节(n<=255)或2个字节(n>255),所以varchar(4),存入3个字符将占用4个字节。

3.char类型的字符串检索速度要比varchar类型的快。

varchar和text:

1.varchar可指定n,text不能指定,内部存储varchar是存入的实际字符数+1个字节(n<=255)或2个字节(n>255),text是实际字符数+2个字节。

2.text类型不能有默认值。

3.varchar可直接创建索引,text创建索引要指定前多少个字符。varchar查询速度快于text,在都创建索引的情况下,text的索引似乎不起作用。

6.日期时间类型

date 日期 '2008-12-2'

time 时间 '12:25:36'

datetime 日期时间 '2008-12-2 22:06:44'

timestamp 自动存储记录修改时间

数据类型的属性

MySQL关键字 含义

NULL 数据列可包含NULL值

NOT NULL 数据列不允许包含NULL值

DEFAULT 默认值

PRIMARY KEY 主键

AUTO_INCREMENT 自动递增,适用于整数类型

UNSIGNED 无符号

CHARACTER SET name 指定一个字符集