1.mysql -h 主机名 -u 用户名 -p
当 MySQL 服务已经运行时, 我们可以通过MySQL自带的客户端工具登录到MySQL数据库中。
-u : 所要登录的用户名;
-p : 告诉服务器将会使用一个密码来登录, 如果所要登录的用户名密码为空, 可以忽略此选项。
2.创建数据库
使用 create database 语句可完成对数据库的创建, 创建命令的格式如下: create database 数据库名 [其他选项];
例如我们需要创建一个名为 my_db 的数据库, 在命令行下执行以下命令: create database my_db character set gbk;
3.创建数据库中的表.
使用 create table 语句可完成对表的创建, create table 的常见形式: create table 表名称(列声明);
以创建 students 表为例, 表中将存放 学号(id)、姓名(name)、性别(sex)、年龄(age)、联系电话(tel) 这些内容:create table students
(
id int unsigned not null auto_increment primary key,
name char(8) not null,
sex char(4) not null,
age tinyint unsigned not null,
tel char(13) null default "-"
);
4.向表中插入数据
insert 语句可以用来将一行或多行数据插到数据库表中, 使用的一般形式如下:
insert [into] 表名 [(列名1, 列名2, 列名3, ...)] values (值1, 值2, 值3, ...);其中 [] 内的内容是可选的, 例如, 要给 my_db 数据库中的 students 表插入一条记录, 执行语句:
insert into students values(NULL, "王三", "男", 20, "13811371377");
5.查询数据
select 语句常用来根据一定的查询规则到数据库中获取数据, 其基本的用法为:
select 列名称 from 表名称 [查询条件];
where 关键词用于指定查询条件, 用法形式为: select 列名称 from 表名称 where 条件;
以查询所有性别为女的信息为例, 输入查询语句: select * from students where sex="女";
6.更新数据
update 语句可用来修改表中的数据, 基本的使用形式为:
update 表名称 set 列名称=新值 where 更新条件;
使用示例: 将id为5的手机号改为默认的"-": update students set tel=default where id=5;
7.删除数据
delete 语句用于删除表中的数据, 基本用法为:
delete from 表名称 where 删除条件;
使用示例: 删除id为2的行: delete from students where id=2;
8.数据库表的修改
1.添加列:基本形式: alter table 表名 add 列名 列数据类型 [after 插入位置];
使用示例: 在表的最后追加列 address: alter table students add address char(60);
2.修改列:基本形式: alter table 表名 change 列名称 列新名称 新数据类型;
使用示例:将表 tel 列改名为 telphone: alter table students change tel telphone char(13) default "-";
3.删除列:基本形式: alter table 表名 drop 列名称;
使用示例:删除 birthday 列: alter table students drop birthday;
4.重命名表:基本形式: alter table 表名 rename 新表名;
使用示例:重命名 students 表为 workmates: alter table students rename workmates;
5.删除表:基本形式: drop table 表名;
使用示例: 删除 workmates 表: dr
9.删除数据库
基本形式: drop database 数据库名;
示例: 删除 my_db 数据库: drop database my_db