MySQL Server 簡介

The materials presented in this web page is provided as is and is used solely for educational purpose. Use at your own risks.
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

請勿轉貼

看其他教材


本文假設你已經安裝了 MySQL Server 5.1.x 版,而且你也依據之前的說明, 建立了使用者 jlu,而且你也為 jlu 建立了一個資料庫 eric,並把這個資料庫 所有權限給了 jlu;也就是說,jlu 可以任意在資料庫 eric 中新增、修改、 以及刪除表格(tables)。

在以下的步驟中,jlu 即將在資料庫 eric 中新增一個表格 Product:

  1. 以 jlu 登入
    // 以 jlu 登入,並使用資料庫 eric
    mysql -u jlu -p eric
    
    // 如果要登入遠端 hostname 的 MySQL Server
    mysql -h hostname -u jlu -p eric
    
    // 如果 jlu 不喜歡或者想更改 root 指定的密碼,可以執行以下指令
    // 同樣的,newpassword 指的是你想輸入的密碼
    set password for jlu@localhost=password('newpassword');
    

  2. 產生表格 Product:每一樣產品包含編號、名稱、價格、以及數量。
    // create table
    create table Product (
      ID int,
      Name varchar(30),
      Price decimal(5,2),
      Qty int);
    
    // 查看 Product 是否已經產生
    // Windows 版產生的 table 名稱變成 product
    show tables;
    
  3. 資料型態:雖然 SQL 有部分資料型態的定義,但大多數的資料庫系統都有其 自己的資料型態的定義,我們在下列資料中,說明幾種比較常見的資料型態。如果 讀者需要進一步的資訊,請到 MySQL 5.1 Reference Manual 中,參考 "Data Types" 的資料。

  4. 為表格 Product 建立範例資料
    insert into Product values (1, 'Monitor', 200.5, 4);
    insert into Product values(2, '無線存取器', 110, 3);
    insert into Product values(3, '無線滑鼠', 11.99, 10);
    insert into Product values(4, '無線輸入超值組合包', 111.99, 8);
    
    // 資料新增之後,檢查一下輸入是否正確
    select * from Product;
    
  5. 執行一些簡單的增、刪、改、查:
    // 查詢所有的產品名稱以及數量
    select Name, Qty from Product;
    
    // 查詢所有價格高於 100 的產品
    select * from Product where Price > 100;
    
    // 查詢編號為 3 的產品名稱以及價格
    select Name, Price from Product where ID = 3;
    
    // 修改編號 3 的產品價格,並利用前一個查詢指令來確認
    update Product set Price=15.3 where ID=3;
    
    // 將編號 3 的產品刪除
    delete from Product where ID=3;
    


Last Updated: Tuesday, 30-Nov-2010 18:19:26 CST
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu