1.表名和列名的命名规则
<1.长度不能超过30个字符;
<2.不能使用orcale的保留字;
<3.不能使用oracle的保留字
<4.只能使用如下字符 A-Z,a-z,0-9,$,#等
2.orcale支持的数据类型
<1.字符型
char 定长 ,最大2000字符;
varchar2(20) 变长,最大4000个字符
clob (character large object) 字符型大对象最大4G
<2.数字型
number(a,b) a表示位数,b表示小位数的位数,b省略不写就表示纯整数
例如:number(5,2) 范围:-999.99~~999.99
<3.日期类型
date 包含年月日和时分秒
timestamp 这是orcale9i对date数据类型的扩张,能表示小数秒
*orcale中默认的日期格式为:‘DD-MON-YY’ eg:'09-6月-99'
*修改日期的默认格式:alter session set nls.date.format='yyyy-mm-dd',该条命令只能临时生效,数据库重启后就失效了,要想永久的进行修改得改其他的配置文件
<4.图片
blob 二进制数据, 可以存放图片/声音 4g
*一般不讲这些东西存放进数据库,除非机密文件,一般放在某个文件夹下
3.约束
约束用于确保数据库数据满足特定的商业规则。在orcale中,约束包括:not null,unique,primary key,foreign key和check五种
4.创建表的语法
创建goods表:
create table goods(
goodsId char(8) constraint pk_goodsid primary key, //主键 (constraint pk_goodsid )可要可不要
goodsName varchar2(20),
unitPrice number(10,2) check(unitPrice>0), //检查约束
category varchar2(8),
provider varchar2(30)
);
创建customer表:
create table customer(
customerId char(8) primary key,
name varchar2(50) not null,
address varchar2(50),
email varchar2(50) unique, //唯一约束
sex char(4) default('男') check(sex in('男','女')), //默认值加检查约束
cardId varchar2(18)
);
创建表purchase
create table purchase(
purchaseId number(2),
purchasename varchar2(20),
customerId char(8) references customer(customerId), //外键约束
goodsId char(8) references goods(goodsId), //外键约束
nums number(5) default(0) check(0<nums and nums<5)
);
5.额外建立约束
如果在建表时忘记建立必要的约束,则可以在建表后使用alter命令为表增加约束,但是要注意:增加not null 约束时需要使用modify选项,而增加其它四种约束使用add选项
以 puchase为例
alter table puchase modify puchasename not null; //建立商品名不能为空的约束
alter table puchase
add constraint pk_purchaseId primary key(purchaseId ), //创建主键约束
add constraint uq_purchasename unique(purchasename ), //创建唯一约束
add constraint ck_nums check(0<nums and nums<5), //check约束
add constraint df_nums default(0) for nums, //默认值约束
add constraint fk_customerId foreign key (customerId) references customer(customerId),
add constraint fk_goodsId foreign key (goodsId ) references customer(goodsId); //外键约束
删除约束
当不需要某个约束的时候,可以删除
alter table 表名 drop constraint 约束名称
特别说明一下:
在删除主键约束的时候,可能有错误,比如:
alter table 表名 drop primary key;
这是因为如果在两张表存在主从关系,那么在删除主表的主键约束时,必须带上cascade选项,此时将破坏主外键关系如
alter table 表名 drop primary key cascade
6.修改表
添加一个字段:alter table goods add(productAddress varchar2(30));
修改字段的长度:alter table goods modify(productAddress varchar2(50));
修改字段的类型:alter table goods modify(productAddress char(50));
修改字段名:alter table BOOK rename column PUBLISHHOURSE to PUBLISHHOUR;
删除一个字段:alter table goods student drop column productAddress ;
修改表的名字:rename goods to goodss;
删改表:drop table purchase ;
7.删除数据
delete from student ;删除所有的记录,表的结构还在,写日志,可以回复的,速度慢
drop table student ; 删除表的结构和数据
truncate table student删除表中所有的记录,表结构还在,不写日志,无法找回删除的记录,速度快
8.将旧表中的数据导入到一个新表中
create table myemp(id,ename,sal)
as select empno,ename,sal
from emp;
该命令将先创建myemp表,然后将emp中相关字段的值导入到myemp表中
列级定义是在定义列的同时定义约束
表级定义是指在定义了所有的列后,再定义约束,这里需要注意,not null约束只能在列级上定义