关系型数据库MySQL
一、表格的概念
表头(header): 每一列的名称;
列(row): 具有相同数据类型的数据的集合;
行(col): 每一行用来描述某个人/物的具体信息;
值(value): 行的具体信息, 每个值必须与该列的数据类型相同;
键(key): 表中用来识别某个特定的人\物的方法, 键的值在当前列中具有唯一性。
二、在 Windows 环境下运行:
启动: net start MySQL 停止: net stop MySQL 卸载: sc delete MySQL
三、数据库操作
1、创建数据库
create database 数据库名 [其他选项];
example:创建一个名为 teacher 的数据库, 在命令行下执行以下命令: create database teacher character set gbk;为了便于在命令提示符下显示中文, 在创建时通过 character set gbk 将数据库字符编码指定为 gbk。
2、创建数据库表
使用 create table 的常见形式: create table 表名称(列声明);
example:创建 students 表为例, 表中将存放 学号(id)、姓名(name)、性别(sex)、年龄(age)、联系电话(tel) 等内容: create table students (
id int unsigned not null auto_increment primary key, //"primary key" 表示该列是表的主键, 本列的值必须唯一;
name char(8) not null, //"not null" 说明该列的值不能为空, 必须要有, 如果不指定该属性, 默认可为空;
sex char(4) not null,
age tinyint unsigned not null, //"unsigned" 加以修饰, 表示该类型为无符号型
tel char(13) null default "-"
);
3、在表中插入数据
insert 用来将一行或多行数据插到数据库表中, 形式如下:
insert [into] 表名 [(列名1, 列名2, 列名3, ...)] values (值1, 值2, 值3, ...); 其中 [] 内的内容是可选的,
例,
要给 mession_db 数据库中的 students 表插入一条记录, 执行语句: insert into students values(NULL, "王名", "女", 20, "13813371377");
有时我们只需要插入部分数据, 或者不按照列的顺序进行插入, 可以使用这样的形式进行插入:
insert into students (name, sex, age) values("孙华", "女", 21);
4、在表中查询数据
select 语句用来根据一定的查询规则到数据库中获取数据, 其基本的用法为:
select 列名称 from 表名称 [查询条件];
例
要查询 students 表中所有学生的名字和年龄, 输入语句 select name, age from students;
使用通配符 * 查询表中所有的内容, 语句: select * from students;
按特定条件查询: where 关键词用于指定查询条件, 用法形式为: select 列名称 from 表名称 where 条件;
以查询所有性别为女的信息为例, 输入查询语句: select * from students where sex="女";
where 子句不仅仅支持 "where 列名 = 值" 这种名等于值的查询形式, 对一般的比较运算的运算符都是支持的
例:
查询名字中带有 "王" 字的所有人信息: select * from students where name like "%王%";
查询id小于5且年龄大于20的所有人信息: select * from students where id<5 and age>20;
5、在表中更新数据
update 语句可用来修改表中的数据, 基本的使用形式为:update 表名称 set 列名称=新值 where 更新条件;
例:
将id为5的手机号改为默认的"-": update students set tel=default where id=5;
将手机号为 13245097888 的姓名改为 "张鹏", 学号改为 012561:
update students set name="张伟鹏", id=012561 where tel="13245097888 ";
6、在表中删除数据
delete 语句用于删除表中的数据,基本用法为: delete from 表名称 where 删除条件;
例:
删除id为2的行: delete from students where id=2;
删除所有年龄小于21岁的数据: delete from students where age<20;
删除表中的所有数据: delete from students;
7、添加列 基本形式: alter table 表名 add 列名 列数据类型 [after 插入位置];
例:
在表的最后追加列 address: alter table students add address char(60);
在名为 age 的列后插入列 birthday: alter table students add birthday date after age;
8、修改列 基本形式: alter table 表名 change 列名称 列新名称 新数据类型;
例:
将表 tel 列改名为 telphone: alter table students change tel telphone char(13) default "-"; 将 name 列的数据类型改为 char(16): alter table students change name name char(16) not null;
9、删除列 基本形式: alter table 表名 drop 列名称;
例:
删除 birthday 列: alter table students drop birthday;