天天看點

MySQL入門-3:安裝與用戶端工具

大綱

1、安裝 MySQL

2、檢索資料

3、資料過濾

一、安裝環境

CentOS-6.5-i386

mysql 5.1.73

為了友善,這裡采用yum方式安裝,對于學習實驗環境完全沒問題,注意下面的操作都以root身份操作。

除非對MySQL需要定制化或者安裝多個執行個體,建議使用YUM/RPM包安裝 或者 通用二進制格式安裝。源碼也有30多M,如果編譯安裝需要花費大量的時間。

MySQL被Oracle收購以後,分為了以下兩個版本

  • Community Edtion (MySQL Community Server)
  • Enterprise Edtion (MySQL Enterprise Server)

MySQL 官方網站提供三種軟體包格式:

  • 軟體包管理特有的格式(RPM包, DEP包,MSI 格式)
  • 通用二進制格式(不需要安裝,解壓并簡單配置即可)
  • 源碼檔案(Source Code)

二、安裝MySQL

a、檢查系統是否已經安裝mysql,如果存在,則解除安裝然後重新安裝

# rpm -qa | grep -i mysql

## 檢視MySQL相關的安裝包
# yum search mysql      

b、安裝mysql伺服器端

# yum -y install mysql-server      

c、安裝mysql用戶端程式

# yum -y install mysql      

d、如果需要開發程式,那麼需要安裝mysql開發庫。建議安裝它

# yum -y install mysql-devel      

e、預設情況下,MySQL的幾個目錄

資料檔案:    /var/lib/mysql
可執行檔案:  /usr/bin (mysql, mysqldump, mysqladmin等指令)
服務啟動腳本:/etc/init.d/mysqld
配置檔案:    /etc/my.cnf      

安裝

mysqld    MySQL伺服器端的二進制可執行檔案

mysql       MySQL用戶端程式

MySQL啟動後,預設情況下監聽在 3306 端口。

三、修改配置檔案

 預設情況下,mysql是不支援中文字元的。因為其預設的字元集latin1,我們可以通過修改其配置檔案,來更改預設的字元集設定。預設情況下的字元集如下:

mysql> SHOW VARIABLES LIKE '%char%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | latin1                     |
| character_set_connection | latin1                     |
| character_set_database   | latin1                     |
| character_set_filesystem | binary                     |
| character_set_results    | latin1                     |
| character_set_server     | latin1                     |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+      

    設定字元集為UTF-8, 編輯配置檔案/etc/my.cnf, 在[mysqld]下添加如下一行:default-character-set=utf8

MySQL入門-3:安裝與用戶端工具

四、啟動 && 停止 MySQL 服務

a、設定mysql開機啟動

# chkconfig --add mysqld
# chkconfig mysqld on
# chkconfig --list | grep mysql      

b、啟動mysql服務

mysq l服務的啟動腳本位于 /etc/init.d/mysqld,我們可以通過以下方式啟動

# service mysqld start
or
# /etc/init.d/mysqld start      
MySQL入門-3:安裝與用戶端工具

c、進行必要的安全性設定

# /usr/bin/mysql_secure_installation      

然後根據提示,回答yes/no即可。

d、重新開機或停止mysql服務

# service mysqld restart     # 重新開機
# service mysqld stop     # 停止      

五、連接配接到 MySQL 服務

    MySQL與所有其他客戶機-伺服器DBMS一樣,要求在能夠執行指令之前登入到DBMS。為了連接配接到MySQL,需要以下資訊:

  • 主機名(如果是連接配接到本地mysql伺服器,為localhost)
  • 端口号(預設為3306)
  • 一個合法的mysql使用者名
  • 使用者密碼(如果需要)
## 連接配接
# mysql -h localhost -P 3306 -u root -p
-h:host指定主機
-P:Port指定端口
-u:user指定使用者名
-p:password

## 退出
mysql> quit      

  在連接配接登入之後,就可以通路該使用者有權限通路的任意資料庫和表了。

MySQL 資料庫的使用者與作業系統使用者無關, 其使用者定義比較特殊: username@host  , 由 使用者名 以及 允許該使用者登入的源主機 組合而成。

a、選擇資料庫

    在最初連接配接到mysql時,沒有任何資料庫打開供你使用。在你能執行任意資料庫操作前,需要選擇一個資料庫。為此,可使用USE關鍵字。例如,為了使用test資料庫

mysql> USE test;      

記住,必須先使用USE選擇資料庫後,才能讀取其中的資料。

b、了解資料庫和表

    想一想,如果你不知道可以使用的資料庫名時怎麼辦?資料庫、表、使用者權限等資訊被存儲在資料庫mysql表中。不過,内部的表一般不能直接通路,可以mysql的SHOW指令來顯示這些資訊。

查詢可用的資料庫:

mysql> SHOW DATABASES;      

擷取資料庫表的清單:

mysql> USE mysql;
mysql> SHOW TABLES;      

檢視表結構:

mysql> DESC user;      

顯示授予使用者的權限:

mysql> SHOW GRANTS;      

更多的SHOW指令, 請

mysql> ? SHOW;

mysql> help contents;      

六、MySQL用戶端工具

1)MySQL

    MySQL是一個簡單的SQL外殼(有GNU readline功能)。它支援互動式和非互動式使用。當互動使用時,查詢結果采用ASCII表格式。當采用非互動式(例如,用作過濾器)模式時,結果為tab分割符格式。可以使用指令行選項更改輸出格式。如果由于結果較大而記憶體不足遇到問題,使用--quick選項。這樣可以強制MySQL從伺服器每次一行搜尋結果,而不是檢索整個結果集并在顯示之前不得不将它儲存到記憶體中。

2)MySQLAdmin

    MySQLAdmin是一個執行管理操作的客戶程式。可以用它來檢查伺服器的配置和目前的狀态,建立并删除資料庫等等。

3) MySQLBinLog

    伺服器生成的二進制日志檔案寫成二進制格式。要想檢查這些文本格式的檔案,應使用MySQLBinLog實用工具。

4) MySQLDump

MySQLDump用戶端可用來轉儲資料庫或搜集資料庫進行備份或将資料轉移到另一個SQL伺服器。轉儲包含建立表和/或裝載表的SQL語句。

5) MySQLImport

MySQLImport實用程式是一個批量加載器,它将文本檔案的内容讀到已有表中。

6) MySQLShow

MySQLShow,客戶可用來很快地查找存在哪些資料庫,資料庫中的表,表中的列或索引。

7) Perror

Perror為系統錯誤代碼或存儲引擎(表處理)錯誤代碼列印其描述資訊。

8) Replace

Replace實用工具可以及時更改檔案或标準輸入中的字元串。它首先使用有限狀态機來比對長的字元串。該工具可以用來交換字元串。

所有用戶端工具,都受my.cnf配置檔案中 [client] 的影響, [mysql] 隻會影響mysql用戶端工具。

所有用戶端工具,都支援一些通用的選項,比如以下這些:

    --user, -u

    --host, -h

    --password, -p

    --port, -P

    --protocol

    --database  DATABASE , -D

MySQL

MySQL用戶端提供兩種工作模式:

  • 互動式模式(這種模式下又可以執行兩類指令)
    • 用戶端指令(help, 可以檢視)
    • 伺服器端指令(需要服務端響應的指令,必須使用語句結束符,預設為 ;)
  • 批處理模式(執行 mysql 腳本)

    # mysql < init.sql   (輸入重定向方式)

    mysql>  source  /path/to/your.sql   (\.)

-------------------讓mysql從檔案中讀取語句----------------- 

--指令行從sql檔案中讀取

# mysql dbname < filename.sql

--mysql會話内從sql檔案讀取

source /path/to/filename.sql

\.  /path/to/filename.sql

1、我們首先看一下mysql 指令的常見選項

[root@mysql ~]# mysql --help
...
Usage: mysql [OPTIONS] [database]
  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup
                      and reconnecting may take a longer time. Disable with
                      --disable-auto-rehash.
                      (Defaults to on; use --skip-auto-rehash to disable.)
  -A, --no-auto-rehash 
                      No automatic rehashing. One has to use 'rehash' to get
                      table and field completion. This gives a quicker start of
                      mysql and disables rehashing on reconnect.
  --auto-vertical-output 
                      Automatically switch to vertical output mode if the
                      result is wider than the terminal width.
  -B, --batch         Don't use history file. Disable interactive behavior.
                      (Enables --silent.)
  
  -C, --compress      Use compression in server/client protocol.
  
  -D, --database=name Database to use.
  --default-character-set=name 
                      Set the default character set.
  --delimiter=name    Delimiter to be used.
  
  -e, --execute=name  Execute command and quit. (Disables --force and history
                      file.)
  -E, --vertical      Print the output of a query (rows) vertically.
  -f, --force         Continue even if we get an SQL error.
  -G, --named-commands 
                      Enable named commands. Named commands mean this program's
                      internal commands; see mysql> help . When enabled, the
                      named commands can be used from any line of the query,
                      otherwise only from the first line, before an enter.
                      Disable with --disable-named-commands. This option is
                      disabled by default.
  
  --local-infile      Enable/disable LOAD DATA LOCAL INFILE.
 
  -h, --host=name     Connect to host.
  -H, --html          Produce HTML output.
  -X, --xml           Produce XML output.
  --line-numbers      Write line numbers for errors.
                      (Defaults to on; use --skip-line-numbers to disable.)
  -L, --skip-line-numbers 
                      Don't write line number for errors.
  -n, --unbuffered    Flush buffer after each query.
 
  -N, --skip-column-names 
                      Don't write column names in results.
  --sigint-ignore     Ignore SIGINT (CTRL-C).
 
  --pager[=name]      Pager to use to display results. If you don't supply an
                      option, the default pager is taken from your ENV variable
                      PAGER. Valid pagers are less, more, cat [> filename],
                      etc. See interactive help (\h) also. This option does not
                      work in batch mode. Disable with --disable-pager. This
                      option is disabled by default.
  -p, --password[=name] 
                      Password to use when connecting to server. If password is
                      not given it's asked from the tty.
  -P, --port=#        Port number to use for connection or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --prompt=name       Set the mysql prompt to this value.
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).

  -S, --socket=name   The socket file to use for connection.
  
  -t, --table         Output in table format.
  --tee=name          Append everything into outfile. See interactive help (\h)
                      also. Does not work in batch mode. Disable with
                      --disable-tee. This option is disabled by default.
  -u, --user=name     User for login if not current user.
  
  --connect-timeout=# Number of seconds before connection timeout.

Default options are read from the following files in the given order:
/etc/mysql/my.cnf /etc/my.cnf ~/.my.cnf 
The following groups are read: mysql client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit. 檢視從配置檔案讀取哪些選項
--no-defaults           Don't read default options from any option file,
                        except for login file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#
                        Also read groups with concat(group, suffix)
--login-path=#          Read this path from the login file.      

2、常用用戶端指令

mysql> ?

For information about MySQL products and services, visit:
   http://www.mysql.com/
For developer information, including the MySQL Reference Manual, visit:
   http://dev.mysql.com/
To buy MySQL Enterprise support, training, or other products, visit:
   https://shop.mysql.com/

List of all MySQL commands:
Note that all text commands must be first on line and end with ';'
?         (\?) Synonym for `help'.
clear     (\c) Clear the current input statement.
connect   (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
edit      (\e) Edit command with $EDITOR.
ego       (\G) Send command to mysql server, display result vertically.
exit      (\q) Exit mysql. Same as quit.
go        (\g) Send command to mysql server.
help      (\h) Display this help.
nopager   (\n) Disable pager, print to stdout.
notee     (\t) Don't write into outfile.
pager     (\P) Set PAGER [to_pager]. Print the query results via PAGER.
print     (\p) Print current command.
prompt    (\R) Change your mysql prompt.
quit      (\q) Quit mysql.
rehash    (\#) Rebuild completion hash.
source    (\.) Execute an SQL script file. Takes a file name as an argument.
status    (\s) Get status information from the server.
system    (\!) Execute a system shell command.
tee       (\T) Set outfile [to_outfile]. Append everything into given outfile.
use       (\u) Use another database. Takes database name as argument.
charset   (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
warnings  (\W) Show warnings after every statement.
nowarning (\w) Don't show warnings after every statement.

For server side help, type 'help contents'      

\c : 清除目前輸入的語句,提前終止、取消語句執行。前提是 \c 之前沒有語句結束符。

delimiter : 設定語句結束符    

\g :  無論語句結束符是什麼,直接将此語句發送至伺服器執行。

\G :  無論語句結束符是什麼,直接将此語句發送至伺服器執行,并且結果以豎排方式顯示。

pager : 通過 PAGER 列印查詢結果

source     \. : 執行SQL 腳本

status      \s :擷取伺服器狀态

system    \! :  執行系統shell 指令

rehash    \# :  對建立的對象(table name, colume name),支援補齊功能

指令補齊功能:

     名稱(table name, colume name)補齊

prompt

    如果有很多mysql資料庫管理,有時會發生自己忘記了在那台伺服器,那台資料庫上,毋庸多說,誰都知道這有多危險。可以使用prompt來重寫mysql用戶端提示符。

mysql>prompt \u@\h(\d) \r:\m:\s> 
\u:連接配接使用者 
\h:連接配接主機 
\d:連接配接資料庫 
\r:\m:\s:顯示目前時間

如果嫌每次都在指令行修改麻煩,直接修改my.cnf參數
[mysql]    #這是不是[mysqld]   
prompt=\\u@\\d \\R:\\m>


root@localhost((none)) 06:57:39> prompt 
Returning to default PROMPT of mysql> 
mysql>      
MySQL入門-3:安裝與用戶端工具

pager

    如果select出來的結果集超過幾個螢幕,那麼前面的結果一晃而過無法看到。使用pager可以設定調用os的more或者less等顯示查詢結果,和在os中使用more或者less檢視大檔案的效果和使用方式都一樣。

pager [cmd]   cmd 是标準linux指令
mysql> pager more
PAGER set to 'more'
mysql> \P more
PAGER set to 'more'
mysql> pager less
PAGER set to 'less'
mysql> \P less
PAGER set to 'less'

// 回到标準輸出stdout
mysql> pager
PAGER set to stdout      

delimiter

delimiter就是告訴MySQL解釋器,指令的結束符是什麼。

預設情況下MySQL指令結束是以分号(;),在寫過程或者函數等情況下,這會産生不少問題,因為存儲過程中有許多語句,是以每一個都需要一個分号。是以你需要選擇一個不太可能出現在你的語句或程式中的字元串作為分隔符。

mysql> delimiter //
mysql> SELECT host,user FROM user//

mysql> delimiter ;      

3、伺服器端指令

For server side help, type 'help contents'

mysql> help contents

mysql> help  KEYWORD      

mysqladmin

用于執行管理性操作。文法是:

shell> mysqladmin [OPTIONS] command [command-option] command ...
通過執行mysqladmin --help,你可以得到你mysqladmin的版本所支援的一個選項清單。
  
目前mysqladmin支援下列指令:
create databasename         //建立一個新資料庫
drop databasename           //删除一個資料庫及其所有表
extended-status              //給出伺服器的一個擴充狀态變量
flush-hosts                  //重新整理所有緩存的主機
flush-logs                   //重新整理所有日志
flush-tables                 //重新整理所有表
flush-privileges             //再次裝載授權表(同reload)
kill id,id,...              //殺死mysql線程
password                     //新密碼,将老密碼改為新密碼
ping                         //檢查mysqld是否活着
processlist                  //顯示服務其中活躍線程清單
reload                       //重載授權表
refresh                      //洗掉所有表并關閉和打開日志檔案
shutdown                     //關掉伺服器
status                       //給出伺服器的簡短狀态消息
         --sleep N
         --count N
variables                    //列印出伺服器變量
version                      //得到伺服器的版本資訊
  
所有指令可以被縮短為其唯一的字首。      

非用戶端工具

myisamchk       # isam 表檢查工具

繼續閱讀