新增数据
数据表写入的数据以行为单位
1、新增数据的语法一:
根据指定列写入值
insert into 表名(列名,列名) values(值,值)
注意点:
写入的值应和列匹配(数量、类型、顺序)
可以不写值得列写成null;
不能写入违背数据表约束条件的值
insert into users(userId,userName,birthday) values(1002,'jack',to_date('1986-10-20','YYYY-MM-DD'));
2、新增数据的语法二:
为表中每列都写入值 ,整表都插入数据
insert into 表名 values (值,值。。)
注意点:
值得数量必须和列的数量要匹配
表中存在默认值则可以使用 default 替入
如果某列不需要写入数据则使用null替入
insert into users(userId,userName,birthday,remoke,sex,age) values(1003,'jerry',sysdate,default,null,null)
3、建表时写入数据
create table 表名 as select * from 表名
新表将具备和原表相同的列名以及数据结构、非空约束,其他约束将不会被复制。
create table new_users as select * from users
4、表数据复制
insert into 新表 select * from 原表
注意点:
复制之前,必须创建新表
新表的数据结构应和查询原表的结果一致。
--复制数据
insert into users_backup select * from users
复制表的结构有一种小技巧:
--复制表的结构
create table users_backup as select * from users where 1=2
5、添加日期类型
获取当前系统时间:sysdate
Oracle中需要将时间进行转换才能写入
to_date('字符型日期','时间格式')
日期格式
YYYY 年
MM 月
DD 天
HH(HH24) 小时(24小时制)
MI 分
SS 秒
to_date('1988-8-15','yyyy-mm-dd'
6、序列
用于按照指定的规则自动生成数据,如人员的编号
在建表时很多时候表中并没有合适的主键,可以使用序列并将该序列作为表中的主键
创建序列
create sequence 序列名
start with 起始值
increment by 增长量
(maxvalue 最大值
可不写
minvalue 最小值)
使用序列
序列名.nextval
删掉序列
drop sequence 序列名
Oracle 中使用 || 表示字符串的拼接
Oracle语句不区分大小写,但是写入数据表的值是区分大小写的。
修改数据
7、修改数据语法
update 表名 set 列=值 where 条件
--对多个列进行修改
update users set age=25,birthday=to_date('1988-8-15','yyyy-mm-dd')
--将编号为1000的用户的年龄改成28
update users set age=28 where userId=1000
--将女生的备注信息改为'女生信息'
update users set remoke='女生信息' where sex='female'
--将年龄在23-25区间的学生的邮箱清空
update users set email=null where age between 23 and 25
update users set email=null where age>=23 and age<=25
update users set email=null where age in(23,24,25)
--将姓名中带有j的用户的邮箱改为'xx@niit.com'同时将他的年龄增加2岁
update users set email='xx@niit.com',age=age+2 where userName like '%j%'
--将没有填写过邮箱用户的邮箱地址设为默认邮箱'xx@niit.com'
update users set email='xx@niit.com' where email is null
--将所有填写过邮箱的用户的邮箱清空
update users set email=null where email is not null
注意点:
如果不写where条件则表中该列所有行都被修改
--整表修改
update users set age=30
where条件的使用
where语句后应为一个表达式,且表达式返回是或否的结果
表达式可以为一个或多个使用逻辑运算符 and 和 or 关联
8、删除数据
delete from 表名 where 条件
有一种方式直接删除表中所有数据
truncate table 表名
--整表删除
truncate table emp
如果要删除的主表的数据在子表被外键所引用,则必须先将子表中的外键数据先删除,才能继续删除数据主表中的数据。
--删除student表的数据
--如果要删除的主表的数据在子表被外键所引用,则必须先将子表中的外键数据先删除后,才能继续删除主表中的数据
delete from student where stuId=1008
--删除student表中的1006的学生数据,由于该条数据被子表引用,因此应该删除子表中对应的数据
delete from score where stuId=1006
delete from student where stuId=1006
主表中的主键是否可以删除
1、如果主键没有被子表引用,则主键可以删除
--1. 如果主键没有被子表引用,则主键可以修改
update student set stuId=1000 where stuId=1008
2、如果主键被子表引用,则该主键无法删除
--2. 如果主键被子表引用,则该主键无法修改
update student set stuId=1000 where stuId=1006