1. 程式人生 > >MySQL簡書

MySQL簡書

簡介

什麼是資料庫

資料庫(Database)是按照資料結構來組織、儲存和管理資料的倉庫。隨著資訊科技和市場的發展,特別是二十世紀九十年代以後,資料管理不再僅僅是儲存和管理資料,而轉變成使用者所需要的各種資料管理的方式。資料庫有很多種型別,從最簡單的儲存有各種資料的表格到能夠進行海量資料儲存的大型資料庫系統都在各個方面得到了廣泛的應用。

主流的資料庫:sqlserver,mysql,Oracle、SQLite、Access、MS SQL Server等。

資料庫管理

  • 將資料儲存到檔案或記憶體
  • 接收待定命令,對檔案進行相應的操作

附:如果有了以上管理系統,無須自己再去建立檔案和資料夾,而是直接傳遞 命令 給上述軟體,讓其來進行檔案操作,他們統稱為資料庫管理系統(DBMS,Database Management System)。

MySQL安裝

MySQL是一種開放原始碼的關係型資料庫管理系統(RDBMS),MySQL資料庫系統使用最常用的資料庫管理語言——結構化查詢語言(SQL)進行資料庫管理。在WEB應用方面MySQL是最好的RDBMS(Relation Database Management System ,關係資料庫管理系統)應用軟體之一。

前提條件

  • 安裝MySQL服務端、客戶端
  • 客戶端連線服務端
  • 客戶端傳送命令給服務端MySQL服務的接受命令並執行相應操作(CRUD等)

下載地址:MySQL

安裝

Windows安裝

首先如果已經安裝MySQL需要重現安裝。

  • 控制面板——程式——解除安裝MySQL
  • 刪除MySQL檔案,example:C盤的programData目錄下顯示隱藏檔案,將MySQL檔案刪除。
  • 刪除登錄檔中的三項:HKEY_LOCAL_MACHINE/SYSTEM/ControlSet001/Services/Eventlog/Application/MySQL                                                           HKEY_LOCAL_MACHINE/SYSTEM/ControlSet002/Services/Eventlog/Application/MySQL                                                           HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Eventlog/Application/MySQL 

Linux安裝

linux版本:CentOS7 64位

  • 下載安裝包“mysql-5.6.33-linux-glibc2.5-x86_64.tar.gz”  
# 安裝依賴
yum -y install perl perl-devel autoconf libaio



把下載的安裝包移動到/usr/local/下。

 

  •     解壓
tar zxvf mysql-5.6.33-linux-glibc2.5-x86_64.tar.gz
  •     複製解壓後的mysql目錄到系統的本地軟體目錄
cp mysql-5.6.33-linux-glibc2.5-x86_64 /usr/local/mysql -r
  •    新增系統mysql組和mysql使用者
groupadd mysql
useradd -r -g mysql -s /bin/false mysql
注意:Because the user is required only for ownership purposes, not login purposes, the useradd command uses the -r and -s /bin/false options to create a user that does not have login permissions to your server host. Omit these options if your useradd does not support them.
  •   進入安裝mysql軟體目錄,修改目錄擁有者為mysql使用者
cd mysql/
chown -R mysql:mysql ./
  •   安裝資料庫,此處可能出現錯誤。
./scripts/mysql_install_db --user=mysql
FATAL ERROR: please install the following Perl modules before executing scripts/mysql_install_db:
Data::Dumper


#解決方法:
yum install -y perl-Data-Dumper
  • 修改當前目錄擁有者為root使用者
chown -R root:root ./
  •     修改當前data目錄擁有者為mysql使用者
chown -R mysql:mysql data

—————————————————————————————————————— 到此資料庫安裝完畢

  •     mysql服務開機自啟動
    新增開機啟動,把啟動指令碼放到開機初始化目錄。
    cp support-files/mysql.server /etc/init.d/mysql
    # 賦予可執行許可權
    chmod +x /etc/init.d/mysql
    # 新增服務
    chkconfig --add mysql 
    # 顯示服務列表
    chkconfig --list 

如果看到mysql的服務,並且3,4,5都是on的話則成功,如果是off,則執行

chkconfig --level 345 mysql on
  •     啟動mysql服務
#建立缺少的資料夾
mkdir /var/log/mariadb
service mysql start
正常提示資訊:Starting MySQL. SUCCESS!
  • 把mysql客戶端放到預設路徑
ln -s /usr/local/mysql/bin/mysql /usr/local/bin/mysql

:建議使用軟鏈過去,不要直接包檔案複製,便於系統安裝多個版本的mysql

通過使用 mysql -uroot -p 連線資料庫(預設資料庫的root使用者沒有密碼,這個需要設定一個密碼)。

錯誤資訊:ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

解決方法:開啟/etc/my.cnf,看看裡面配置的socket位置是什麼目錄。“socket=/var/lib/mysql/mysql.sock”路徑和“/tmp/mysql.sock”不一致。建立一個軟連線:ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock

到這裡任務算是完成了。之後就可以建立資料庫使用者,然後使用資料庫了。

 

許可權控制

  • 去除匿名使用者
# 測試匿名使用者登入
mysql -ux3

可以看到匿名使用者可以登入,具有information_schema和test庫的相關許可權。

# 刪除匿名使用者,使用root使用者登入資料庫
delete from mysql.user where User='';
flush privileges;

再次測試匿名使用者登入

 

 

MySQL操作

連線資料庫

mysql  -u user -p                   例:mysql -u root -p
  •  常見錯誤
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2), it means that the MySQL server daemon (Unix) or service (Windows) is not running.
  • 退出連線
QUIT 或者 Ctrl+D

檢視、建立

 

 

預設資料庫:
             mysql - 使用者許可權相關資料
             test - 用於使用者測試資料
             information_schema - MySQL本身架構相關資料
 
建立資料庫:     
               create database db1 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;     # utf8編碼
               create database db1 DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci; # gbk編碼
使用資料庫:     use db1;

 

 

 

  •  顯示當前使用的資料庫中所有表:SHOW TABLES;

使用者管理

建立使用者
    create user '使用者名稱'@'IP地址' identified by '密碼';
刪除使用者
    drop user '使用者名稱'@'IP地址';
修改使用者
    rename user '使用者名稱'@'IP地址'; to '新使用者名稱'@'IP地址';;
修改密碼
    set password for '使用者名稱'@'IP地址' = Password('新密碼')

注:使用者許可權相關資料儲存在mysql資料庫的user表中,所以也可以直接對其進行操作(不建議)

許可權管理

mysql對於許可權的限制:

  • 資料庫及內部其他許可權
            資料庫名.*           資料庫中的所有
            資料庫名.表          指定資料庫中的某張表
            資料庫名.儲存過程     指定資料庫中的儲存過程
            *.*                所有資料庫
  • 使用者和IP的許可權
            使用者名稱@IP地址         使用者只能在改IP下才能訪問
            使用者名稱@192.168.1.%   使用者只能在改IP段下才能訪問(萬用字元%表示任意)
            使用者名稱@%             使用者可以再任意IP下訪問(預設IP地址為%)
  • 檢視許可權
show grants for '使用者'@'IP地址' 
  • 授權
grant  許可權 on 資料庫.表 to   '使用者'@'IP地址'
  • 取消授權
revoke 許可權 on 資料庫.表 from '使用者'@'IP地址'
授權例項:

grant all privileges on db1.tb1 TO '使用者名稱'@'IP'

grant select on db1.* TO '使用者名稱'@'IP'

grant select,insert on *.* TO '使用者名稱'@'IP'

revoke select on db1.tb1 from '使用者名稱'@'IP'

 

mysql表操作

  • 查看錶
show tables;                    # 檢視資料庫全部表

select * from 表名;             # 查看錶所有內容
  • 建立表
create table 表名(
    列名  型別  是否可以為空,
    列名  型別  是否可以為空
)ENGINE=InnoDB DEFAULT CHARSET=utf8
例項

CREATE TABLE `tab1` (
  `nid` int(11) NOT NULL auto_increment,                   # not null表示不能為空,auto_increment表示自增
  `name` varchar(255) DEFAULT zhangyanlin,                 # default 表示預設值
  `email` varchar(255),
  PRIMARY KEY (`nid`)                                      # 把nid列設定成主鍵
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

注:

  1. 預設值,建立列時可以指定預設值,當插入資料時如果未主動設定,則自動新增預設值
  2. 自增,如果為某列設定自增列,插入資料時無需設定此列,預設將自增(表中只能有一個自增列)注意:1、對於自增列,必須是索引(含主鍵)2、對於自增可以設定步長和起始值
  3. 主鍵,一種特殊的唯一索引,不允許有空值,如果主鍵使用單個列,則它的值必須唯一,如果是多列,則其組合必須唯一。
  • 刪除表
drop table 表名
  • 清空表內容
delete from 表名
truncate table 表名
  • 修改表
    新增列:   alter table 表名 add 列名 型別
    刪除列:   alter table 表名 drop column 列名
    修改列:
              alter table 表名 modify column 列名 型別;  -- 型別
              alter table 表名 change 原列名 新列名 型別; -- 列名,型別
      
    新增主鍵:
              alter table 表名 add primary key(列名);
    刪除主鍵:
              alter table 表名 drop primary key;
              alter table 表名  modify  列名 int, drop primary key;
      
    新增外來鍵: alter table 從表 add constraint 外來鍵名稱(形如:FK_從表_主表) foreign key 從表(外來鍵欄位) references 主表(主鍵欄位);
    刪除外來鍵: alter table 表名 drop foreign key 外來鍵名稱
      
    修改預設值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
    刪除預設值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;

    推薦使用Navicat Premium。

  • 基本資料型別

MySQL的資料型別大致分為:數值、時間和字串

mysql表內容操作

1、增

insert into 表 (列名,列名...) values (值,值,...)
insert into 表 (列名,列名...) values (值,值,...),(值,值,值...)
insert into 表 (列名,列名...) select (列名,列名...) from 表
例:
    insert into tab1(name,email) values('zhangyanlin','[email protected]')
2、刪

delete from 表                                      # 刪除表裡全部資料
delete from 表 where id=1 and name='zhangyanlin'   # 刪除ID =1 和name='zhangyanlin' 那一行資料
3、改

update 表 set name = 'zhangyanlin' where id>1
4、查

select * from 表
select * from 表 where id > 1
select nid,name,gender as gg from 表 where id > 1
a、條件判斷where

    select * from 表 where id > 1 and name != 'aylin' and num = 12;
    select * from 表 where id between 5 and 16;
    select * from 表 where id in (11,22,33)
    select * from 表 where id not in (11,22,33)
    select * from 表 where id in (select nid from 表)
b、萬用字元like

    select * from 表 where name like 'zhang%'  # zhang開頭的所有(多個字串)
    select * from 表 where name like 'zhang_'  # zhang開頭的所有(一個字元)
c、限制limit

    select * from 表 limit 5;            - 前5行
    select * from 表 limit 4,5;          - 從第4行開始的5行
    select * from 表 limit 5 offset 4    - 從第4行開始的5行
d、排序asc,desc

    select * from 表 order by 列 asc              - 根據 “列” 從小到大排列
    select * from 表 order by 列 desc             - 根據 “列” 從大到小排列
    select * from 表 order by 列1 desc,列2 asc    - 根據 “列1” 從大到小排列,如果相同則按列2從小到大排序
 e、分組group by

    select num from 表 group by num
    select num,nid from 表 group by num,nid
    select num,nid from 表  where nid > 10 group by num,nid order nid desc
    select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid
    select num from 表 group by num having max(id) > 10
 
    特別的:group by 必須在where之後,order by之前