資料庫和資料表的基本操作
阿新 • • 發佈:2018-11-25
一、資料庫的操作
// 登陸mysql資料庫
mysql -u root -p;
// 建立資料庫
CREATE DATABASE db_book;
// 檢視所有資料庫
SHOW DATABASE;
// 選擇資料庫
USE db_book;
// 檢視所有資料表
SHOW TABLES;
// 刪除資料庫
DROP DATABASE db_book;
二、資料表的基本操作
CREATE TABLE t_bookType(
`id` int primary key auto_increment,
`bookTypeName` varchar(20)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
// constraint fk foreign key (bookTypeId) references t_bookType(id) 設定外來鍵
CREATE TABLE t_book(
`id` int primary key auto_increment,
`bookName` varchar(20),
`author` varchar(20),
`price` decimal(6,2),
`bookTypeId` int,
constraint fk foreign key (bookTypeId) references t_bookType(id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
// 如果你不想欄位為 NULL 可以設定欄位的屬性為 NOT NULL,
// 在操作資料庫時如果輸入該欄位的資料為NULL ,就會報錯。
// AUTO_INCREMENT定義列為自增的屬性,一般用於主鍵,數值會自動加1。
// PRIMARY KEY關鍵字用於定義列為主鍵。 您可以使用多列來定義主鍵,列間以逗號分隔。
// ENGINE 設定儲存引擎,CHARSET 設定編碼。
// 最後一行不需要逗號。編碼是utf8,如果編碼和插入資料型別不對應則會報錯
CREATE TABLE IF NOT EXISTS `tb_student`(
`id` VARCHAR(10),
`name` VARCHAR(10) NOT NULL,
`gender` VARCHAR(4) NOT NULL,
`score` INT,
PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
// 查看錶結構
desc t_bookType;
// 重命名錶名
alter table t_book rename t_book2;
// 重新命名欄位名
alter table t_book change bookName bookName2 varchar(20);
// 新增欄位(first表示在新增到第一行,after表示在某一個欄位後面新增)
alter table t_book add testField int after author;
// 修改表中某一欄位的資料型別
alter table tb_student modify score INT NOT NULL;
// 刪除欄位
alter table t_book drop testField;
// 刪除表(不能先刪除有外來鍵約束的表)
drop table test;
三、資料表的插入、更新和刪除操作
/**** 1、插入操作 ****/
// 向資料庫中插入表中的資料
INSERT INTO tb_student ( id, name, gender, score ) VALUES ( "2018-1", "Eric1", "男", "66");
INSERT INTO tb_student ( id, name, gender, score ) VALUES ( "2018-2", "Eric2", "女", "78");
INSERT INTO tb_student ( id, name, gender, score ) VALUES ( "2018-3", "Eric3", "男", "81");
INSERT INTO tb_student ( id, name, gender, score ) VALUES ( "2018-4", "Eric4", "男", "66");
INSERT INTO tb_student ( id, name, gender, score ) VALUES ( "2018-5", "Eric5", "女", "88");
INSERT INTO tb_student ( id, name, gender, score ) VALUES ( "2018-6", "Eric6", "男", "84");
INSERT INTO tb_student ( id, name, gender, score ) VALUES ( "2018-7", "Eric7", "男", "93");
INSERT INTO tb_student ( id, name, gender, score ) VALUES ( "2018-8", "Eric8", "女", "93");
INSERT INTO tb_student ( id, name, gender, score ) VALUES ( "2018—9", "Eric9", "男", "99");
/**** 2、更新操作 ****/
UPDATE tb_student SET score=66 WHERE id="2018-4"; // 將id為2018-4的欄位中的score修改為66
/**** 3、刪除操作 ****/
DELETE FROM tb_student WHERE id="2018-4"; // 將id為2018-4的欄位刪除,如果沒有where則刪除所有欄位