数据库DDL和DML操作

  转载自 数据库:DDL 和 DML操作

一,DDL操作 对数据库中的某些对象(例如,database,table)进行管理,如Create,Alter和Drop.

1.操作数据库

--创建数据库
create database if not exists dbname;

--销毁数据库
drop databasae if exists dbname;

2.操作数据库表

2.1 添加字段

--追加字段
alter table tname add 字段名称 类型(长度);、

--添加字段到第1列
alter table tname add 字段名称 类型(长度) first;

--添加字段到指定列后面
alter table tname add 字段名称 类型(长度) after 指定列名;

2.2删除字段

alter table tname drop 字段名称;

2.3修改字段:名称,类型,长度,约束描述等

alter table tname modify 字段名称 新类型 新约束;

alter table tname change 旧字段名 新字段名 新类型 新约束;

2.4修改表名

rename table tname to new_tname;

2.5删除数据库表

drop table tname;

二,DML操作 对数据库中的数据进行一些简单操作,如insert,delete,update,select等.

1.insert

1.1 语法格式

insert into tname[(fie1,fie2,...)] values(val1,val2,...);

1.2 单条插入

#插入一条完整的记录:值的顺序要和表中字段的顺序保持一致
insert into stu values('haha@163.com', 'zs', 18, '', '13211111111');

#插入记录:ls 20 女,声明字段的顺序可以任意,值的顺序与声明的字段的顺序保持一致
insert into stu(sname, age, sex) values('ls', 20, '');

1.3 批量插入

#插入3条记录(批量插入):ww 23 男 zl 34 男 haha 24 女,效率高,因为I/O操作少。
insert into stu(sname, age, sex) values('ls', 20, ''),('zl', 34, ''),('haha', 20, '');

1.4复制表

#复制表:stu表 -> student表。思路:1.创建student表,结构类似(结构复制);2.查询stu表插入到student表中。

方法一:
select * from stu where 1=0;#一条数据也没查到,因为条件不成立,但是结果集中是有表结构的
create table student select * from stu where 1=0;#复制表结构
insert into student select * from stu;#查询并插入数据

方法二:
create table stu1 select * from stu;#复制表结构及其数据

1.5 插入日期

alter table stu add bir date;#添加字段
insert int stu values('hehe', 20, '', '13211111111', '1996-06-06');#'1996-06-06' 是字符串

2.delete

语法格式:
delete from tname [where condition];

实例代码:
delete from stu where sname='haha';

3.update

语法格式:
update tname set fie1 = val1, fie2=val2,... [where condition]

实例代码:
update stu set age=28 where sname='zs';#where后的条件字段必须唯一确定该条记录:主键
原文地址:https://www.cnblogs.com/cxy0210/p/14710401.html