MySQL基礎 語句實際演練
在一個運行MySQL的服務器上,實際上可以創建多個數據庫(Database)。要列出所有數據庫,使用命令:
mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | shici | | sys | | test | | school | +--------------------+
其中,information_schema
、mysql
、performance_schema
和sys
是系統庫,不要去改動它們。其他的是用戶創建的數據庫。
要創建一個新數據庫,使用命令:
mysql> CREATE DATABASE test; Query OK, 1 row affected (0.01 sec)
要刪除一個數據庫,使用命令:
mysql> DROP DATABASE test; Query OK, 0 rows affected (0.01 sec)
注意:刪除一個數據庫將導致該數據庫的所有表全部被刪除。
對一個數據庫進行操作時,要首先將其切換為當前數據庫:
mysql> USE test; Database changed
表
列出當前數據庫的所有表,使用命令:
mysql> SHOW TABLES; +---------------------+ | Tables_in_test | +---------------------+ | classes | | statistics | | students | | students_of_class1 | +---------------------+
要查看一個表的結構,使用命令:
mysql> DESC students; +----------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+----------------+ | id | bigint(20) | NO | PRI | NULL | auto_increment | | class_id | bigint(20) | NO | | NULL | | | name | varchar(100) | NO | | NULL | | | gender | varchar(1) | NO | | NULL | | | score | int(11) | NO | | NULL | | +----------+--------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec)
還可以使用以下命令查看創建表的SQL語句:
mysql> SHOW CREATE TABLE students; +----------+-------------------------------------------------------+ | students | CREATE TABLE `students` ( | | | `id` bigint(20) NOT NULL AUTO_INCREMENT, | | | `class_id` bigint(20) NOT NULL, | | | `name` varchar(100) NOT NULL, | | | `gender` varchar(1) NOT NULL, | | | `score` int(11) NOT NULL, | | | PRIMARY KEY (`id`) | | | ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 | +----------+-------------------------------------------------------+ 1 row in set (0.00 sec)
創建表使用CREATE TABLE
語句,而刪除表使用DROP TABLE
語句:
mysql> DROP TABLE students; Query OK, 0 rows affected (0.01 sec)
修改表就比較復雜。如果要給students
表新增一列birth
,使用:
ALTER TABLE students ADD COLUMN birth VARCHAR(10) NOT NULL;
要修改birth
列,例如把列名改為birthday
,類型改為VARCHAR(20)
:
ALTER TABLE students CHANGE COLUMN birth birthday VARCHAR(20) NOT NULL;
要刪除列,使用:
ALTER TABLE students DROP COLUMN birthday;
退出MySQL
使用EXIT
命令退出MySQL:
mysql> EXIT Bye
注意EXIT
僅僅斷開了客戶端和服務器的連接,MySQL服務器仍然繼續運行。