1. 程式人生 > 實用技巧 >SQL 資料庫的基本操作

SQL 資料庫的基本操作

##DDL和DML DDL定義語言
-- 



--  1.建立資料庫


--  檢視資料庫 
show databases
#  建立資料庫 sql語言不區分大小寫,除非是在字串中區分
create database Helloworld;
#  如果資料庫不存在就建立
create database if not exists helloworld ;
#修改資料庫字符集為utf8
create database if not exists helloworld DEFAULT charset utf8;
# 刪除資料庫
drop database helloworld;

# 使用資料庫
use classes;
#檢視資料庫
show tables from world;

#建立資料表
-- 姓名SQL語言沒有單個字元和字串的區分,只用varchar表示
create table if not exists students_db1(
s_bir  date,-- 日期型別
s_id int, -- 學號
s_name varchar(20), -- 名稱
s_sex  varchar(4) -- 性別

);

#修改表結構 增加資料庫表中列的欄位,只能在尾部插入該列的欄位
alter table student add s_cid int;

#修改表中列的資料名稱 或者欄位儲存大小
alter table student modify column s_name varchar(40) ;

#刪除表中某一列
alter table student drop column s_sex ;

#修改表中列的名稱
alter table student modify column s_name to s_name_1;

#查看錶結構 -查看錶中列的欄位屬性
desc student;

# 刪除資料表
drop table students_db1;

#修改資料庫名稱
rename  table students_db1 to student;


#DML  資料庫操作<插入><刪除><修改><查詢>

#資料插入
insert into student values('1991-06-01',1,'王',1001),
('1991-06-02',2,'王',1002),
('1991-06-03',3,'王',1003),
('1991-06-04',4,'王',1004),
('1991-06-05',5,'王',1005);

#插入部分資料
#insert into <表名><欄位名稱> values<新增的資料>
insert into student(s_name,s_cid ,s_id)values('王',1,1111);
#查詢
select * from student where s_id=1 limit 100;

//修改列中資料內容
update student set s_id=333 where s_cid=1001;

#多條件修改
update student set s_bir='2020-01-01' where s_id=333 or s_cid=1001;


#刪除資料
delete from student  where s_cid=1001;
 
#多條件刪除表中資料
delete from student where s_id=2 and s_name='王';

#刪除表中所有資料
DELETE from student;