MySQL常用指令:
1.命令行启动mysql :
c:/>mysql -h hostname -u root -p
或
c:/>mysql -u root -p root (密码)
或
c:/>mysql -uroot -proot (密码)
(windows平台 需要将mysql加入Path环境变量中)

(-p 后接密码后回车 也可以 回车后输入密码)
若连接本地数据库 -h hostname 改为 -h localhost 或者省略-h hostname(即为mysql -u root -p)
若连接远端服务器的数据库 -h hostname 改为 -h + 192.168.X.X (远程服务器的IP地址)
2.查看mysql的帮助:
c:/> mysql --help

3.查看现在时间:
select current_date;
select now();


mysql是一个数据库软件 数据库是表的集合
mysql里面可以有很多数据库(可以理解为很多表的集合)
4.显示mysql里面有多少数据库:
show databases;

5 sql注释语句:
mysql > -- 注释内容
注意 -- 和注释之间有个空格!

6 创建数据库:
create database 数据库名称
mysql > create database mybase;

7 删除数据库:
drop database 数据库名称:
mysql > drop database mybase;

8 使用指定的数据库:
use + 指定的数据库名称
mysql > use myhive;

9 指定数据库后显示数据库中所有表:
mysql > show tables;

Empty set 标识表空
10 在数据库中创建表:


11 查看数据表:
mysql > show create table test;
mysql > desc test;
mysql > describe test;
(test 为一个表名)



查看表结构:

12 删除表:
mysql > drop table test;

13 查询表数据:
mysql > select * from test;
(全字段 全表扫描)
或者:
mysql > select id,name from test;
(部分字段查询 投影查询)

条件查询 查id>3的字段:

其他查询注意:








14 插入记录:
mysql > insert into test(id,name,age) values(1,'wang',23);

或插入部分字段数据:
mysql > insert into test(id,name) values(1,'wang');

若插入全部字段可以简写:
mysql > insert into test values(1,'wang',59);

15 更新记录:


mysql > update test set grade=11 where id = 2;

16 删除记录:
mysql > delete from test where id=1;

注意,若:
mysql > delete from test;
则会把所有记录删除,要谨慎!
小总结:
CRUD:
create:
insert into table_name(field_name,...) values(value,...);
retrieve:
select id ,... from table_name where id=xxx,...;
update:
update table_name set id=xxx,... where id=xxx,...;
delete:
delete from test where ...;
MySQL约束:
1 primary key 主键
主键特点:不为null 不能重复
mysql > create table test(id int primary key,...);
2 自增
mysql > create table test(id int primary key auto_increment,...);
自增是查询到最大值后+1
3 不能为空 not null:
mysql > create table test(id int primary key auto_increment, name varchar(20) not null, age int);
4 带条件创建 删除:
// 带条件创建
mysql > create database if not exists itcast;
mysql > create table if not exists test;
// 带条件删除
mysql > drop database if exists itcast;
mysql > drop table if exists test;
设一个字段为空值:
update test set name=null where id=3;

注意:需要在设计表中允许name字段为空 才能在客户端用指令设置空值

设置字段为null后 我们来查询为null的字段:

可见查询 null 比较特殊 不能用:
mysql > ... where name=null;
而应该:
mysql > ... where name is null;
来看个特Null情况:

来个段子:
比如你问我:“那个人叫什么名字”?
我说:“不知道”。
不知道 可能是那个人叫不知道,也可能是我真不知道。
这就是两种Null的区别...

所以要特别注意Null
拓展:
使用MySQL命令行执行sql脚本:
mysql > source d:/java/xxx.sql;
更多内容下载ppt学习:
http://pan.baidu.com/s/1hs3QDvQ
网友评论