資料庫 01 增刪改

2021-10-23 09:37:03 字數 3030 閱讀 5978

登入:win+r --> cmd --> mysql -hloaclhost -uroot -ppassword

退出:exit 或 quit

資料庫:database,儲存有組織的資料的容器

表: table, 某種特定型別資料的結構化清單

模式: schema, 關於資料庫和表的布局及特性資訊

列: column, 表中的乙個字段,所有表都是由乙個或多個列組成

行: row, 表中的乙個記錄

主鍵 primarykey 能夠唯一區分表中每個行,唯一標識每行的這個列稱為主鍵

外來鍵 foreignkey

關鍵字:keyword 不要用關鍵字命名乙個表或列

主鍵的好習慣

建立資料庫:create database mcc;

檢視資料庫:show databases;

使用資料庫:use mcc

需先用use開啟資料庫,才能讀取該庫中的資訊

檢視資料庫中的表:show tables;

目前還沒有表,建立表

建立表

create table customers if not exists(

cust_id int not null auto_increment,

cust_name char(50) not null,

cust_address cahr(50) null,

cust_city cahr(50) null,

cust_state cahr(50) not null default 1,

cust_zip cahr(50) null,

cust_country cahr(50) null ,

cust_contact cahr(50) null,

cust_email cahr(255) null,

primary key (cust_id)

)engine=innodb;

if not exists:檢視表名是否存在,僅在表名不存在時建立

null:允許插入行時不給出該列的值,為預設設定

not null:插入行時,該列必須有值

注:null是沒有值,『』空串是乙個有效的值

primary key

可以在字段後面指定:***字段 primary key

也可以在最後專門一行指定:primary key(***)或primary key(***,yyy)

主鍵是唯一標識,只能使用不允許null值的列

auto_increment:每個表只允許乙個此種列,且它必須被索引,如使其成為主鍵

插入資料時,由於該字段是自增的且非空的,所以該字段值可以使用null

也可以是插入資料時指出需要插入資料的字段,該auto_increment欄位可以不指定

insert into customers(cust_name,cust_city) values (『llll』,『shanghai』)

default:設定預設值,預設值支援常量,不允許使用函式

檢視表結構

1)desc test2;

2)describe test2;

3)show columns from test2;

更改表結構

注一般建立表時應該花大量事件來設計,盡量不更改表結構

要改的話,最好先進行完整備份,包括模式和資料

1)alter table customers

add test_column char(30);

2)drop column test_column

刪除表:drop table customers;

重新命名表:rename table customers to customers_bak

插入資料:insert

1)insert low_priority into test2 values(2,『lilili』)

2) 插入多行

insert into test2 values (1,『li』);

insert into test2 values (2,『lili』);

3)插入多行

insert into test2 values (***,***xx),(yyy,yyyy)

4)insert select

insert low_priority into test2(name) select name from test55;

insert low_priority into test2 select * from test55;

insert low_priority into test2 select * from test55 where age > 18;

更新資料:update 也可刪除某列資料

update ignore test2 set age = 18;

update ignore test2 set age = 18 where name = 』 lihao ';

update ignore test2 set age = 18 ,id = 666 where name = 』 lihao ';

刪除某列的值,可將其設定為null

update test2 set age=null;

刪除資料:delete 刪除某行資料

delete from test2 where name=『lihao』;

delete from test2;

truncate table test2;

資料庫增刪改查

我們知道當我們的表建立後重複執行會出錯,一般我們會這麼處理 create table if not exists stuinfo 學了新建表我們還應該知道乙個東西,如何刪除表 deop table table name 怎麼檢視別人的見表語句呢 show create table stuinfo 怎...

資料庫簡單增刪改

記得大一時對資料庫還是比較感冒的,但是現在叫我再像以前一樣去寫sql語句似乎有點難,分享乙份增刪改吧 資料庫語句 ddl語句 建立表和刪除表 create和drop 建立表的sql語句 欄位id代表主鍵 唯一 欄位name等等,欄位名後面跟型別 除開主鍵型別其實可以不寫 create table i...

資料庫增刪改查

import pymysql def getmysqlconn conn pymysql.connect host 172.16.238.130 port 3306,db my mysql user root password 123456 charset utf8 return conn def ...